8

I want to call a function with call_user_func_array but i noticed that if an argument is a reference in the function definition and is a simple value in call_user_func_array, the following warning appears: Warning: Parameter 1 to test() expected to be a reference, value given

Here is a simple example of what i am trying to do:

<?php
$a = 0;
$args = array($a);
function test(&$a) {
    $a++;
}
$a = 0;
call_user_func_array('test', $args);
?>

My question is: how can i know if a value (in this case the first value of $args) is a reference or not ?

2 Answers 2

4

No, the issue is that the first parameter of the function is pass-by-reference (meaning the function can modify the argument in the caller's scope). Therefore, you must pass a variable or something which is assignable as the first argument. When you create the array like array($a), it just copies the value of the variable $a (which is 0) into a slot in the array. It does not refer back to the variable $a in any way. And then when you call the function, it is as if you're doing this, which does not work:

test(0)

If you really wanted to, you could put $a into the array by reference, but it's kinda tricky:

<?php
$a = 0;
$args = array(&$a);
function test(&$a) {
    $a++;
}
call_user_func_array('test', $args);
?>

As to how you would tell, that the array element is a reference... that is hard. You could do var_dump() on the array, and search for the "&" symbol:

> var_dump($args);
array(1) {
  [0]=>
  &int(1)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, i know that the code works that way. I just wanted a way to make sure that the $args array (that can contains about anything, since in my code it is passed by another function) has been created that way in order to avoid any error when i call call_user_func_array. That's why i wanted to know how to check if the variables in the array were references or not.
1

Check out the comments on this PHP documentation page:

http://php.net/manual/en/language.references.spot.php

2 Comments

All i see is functions to check if two arrays/objects/variables are pointing to the same memory area by modifying one and checking if the other one is modified too. In my code (not the example, the real one), i only have the array of arguments and i want to know if one argument is a reference. That way, i can throw an error if the callback function wants a reference and the array contains a simple value.
It already triggers a warning, which is intended for developers. What sort of error do you want? You could set a custom error handler if you want to alter the behaviour

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.