Can PHP callback accept its parameters (links) by reference?

I tested the following and it works on both PHP 5.2 and 5.3, however it is not documented anywhere as far as I can see, so I appreciate its use.

I have a function in a class called isValid, this checks the hash to see if the given value is in the set of valid values. There are some meanings that are valid but outdated; I would like my isValid function to update the passed value to the current one and return true.

Well, when I call it myself, I would like to use this method when it is used as a callback to array_filter.

Here's a test case that, as expected, leads to an array with values ​​2,3,4,5,6.

<?php $test = array(1, 2, 3, 4, 5); echo print_r(array_filter($test, 'maptest'), true); function maptest(&$value) { $value ++; return true; } 

So, StackOverflow: is it allowed or is it undocumented functions that may disappear / stop working / cause errors in the future?

+7
arrays reference php callback array-filter
source share
2 answers

Yes, it is allowed.

In this regard, there is nothing special about calling functions via callbacks.

However, your specific example does not illustrate one difficulty. Consider:

 function inc(&$i) { $i++; } $n = 0; // Warning: Parameter 1 to inc() expected to be a reference, value given: call_user_func('inc', $n); 

The problem is that you pass $n to call_user_func , and call_user_func does not take values ​​by reference. Therefore, by the time inc appears, it will not receive a link. This is not a problem with array_filter , because it passes the array directly and can directly pass variables in the array to the callback function.

You can use call-by-pass-by-reference, but this is deprecated and removed from trunk:

 function inc(&$i) { $i++; } $n = 0; // Deprecated: Call-time pass-by-reference has been deprecated call_user_func('inc', &$n); 

So the best option is to use call_user_func_array instead:

 function inc(&$i) { $i++; } $n = 0; call_user_func_array('inc', array(&$n)); 

This function will pass by reference elements that have the is_ref flag, and others will pass by value.

+8
source share
+1
source share

All Articles