views:

207

answers:

3

Hello, 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 ?

A: 

Check out the comments on this PHP documentation page:

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

Tim Sylvester
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.
Gu1
A: 

I think i found a way... I will simply do something like:

$args[0] = &$args[0];

if $args[0] was already a reference, this a no impact and if it was not a reference it is now one so, there won't be any warning.

Gu1
+1  A: 

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)
}
newacct
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.
Gu1