Jump to content

Method WireArray::each() doesn't work as expected


kixe
 Share

Recommended Posts

I have a function with one single parameter ($page). The function sets a page property and return nothing.
If I call the function in 2 different ways, one works, the other one not.
 

function preparePost($item) {
 $item->set('foo','bar');
}

$featured = $pages->find($selectorstring);

$featured->each('preparePost'); // doesn't work

var_dump($featured->each('foo'));
/** doesn't work, return
 * array (size=2)
 * 0 => null
 * 1 => null
 */

foreach ($featured as $item) preparePost($item); // works

var_dump($featured->each('foo'));
/** works, return
* array (size=2)
* 0 => string 'bar' (length=3)
* 1 => string 'bar' (length=3)
*/

Any ideas?

Link to comment
Share on other sites

Wouldn't it be as below?

function preparePost($item) {
 $item->set('foo','bar');
}

$featured = $pages->find($selectorstring);

$featured->each(preparePost($item));

var_dump($featured->each('foo'));
Link to comment
Share on other sites

$featured->each(function($item){
  $item->set('foo', 'bar');
});

//or 

$preparePost = function($item){
  $item->set('foo', 'bar');
};

$featured->each($preparePost);

A plain string is not a valid callable, therefore your version isn't supposed to work.

Link to comment
Share on other sites

After digging a while I found out it has to do with namespace.

"is_callable() doesn't seem able to resolve namespaces. If you're passing a string, then the string has to include the function's full namespace."
found here: php.net/manual/en/function.is-callable.php#107105
 

$featured->each('\ProcessWire\preparePost'); // works
$featured->each(__NAMESPACE__.'\preparePost'); // works
$featured->each('preparePost'); // works ONLY if no namespace is declared

I posted an issue on github:
https://github.com/ryancramerdesign/ProcessWire/issues/1869

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...