Villermen Villermen - 1 year ago 61
PHP Question

Callback function not found while it is defined above

I have this code snippet that is supposed to find the differences between two arrays of feed items:

protected function execute()
$existingFeedItems = $feed->getItems();
$newFeedItems = $feed->loadItems();

function compareFeedItemIds($feedItem1, $feedItem2)
return $feedItem1->getFeedItemId() == $feedItem2->getFeedItemId() ? 0 : -1;

$feedItemsAdded = array_udiff($newFeedItems, $existingFeedItems, "compareFeedItemIds");
$feedItemsRemoved = array_diff($existingFeedItems, $newFeedItems, "compareFeedItemIds");
$unchangedFeedItems = array_uintersect($newFeedItems, $existingFeedItems, "compareFeedItemIds");

This will throw the error:

Warning: array_udiff() expects parameter 3 to be a valid callback,
function 'compareFeedItemIds' not found or invalid function name

Even though I have defined that function above. What is the reason for PHP throwing this error? I have to add I am executing this from an object's method context.

Answer Source

If your callback function is defined within a namespace, then you need to indicate that namespace when you make the udiff() call.

$feedItemsAdded = array_udiff($newFeedItems, $existingFeedItems, "namespace\\compareFeedItemIds");

Otherwise PHP will search for the callback function in the global namespace