PHP How do I know if a variable is a link?

I want to call a function using call_user_func_array, but I noticed that if the argument is a link in the function definition and is a simple value in call_user_func_array, the following warning appears: Warning: Parameter 1 to check () is expected as a reference, the value given

Here is a simple example of what I'm 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 find out if a value (in this case, the first value of $ args) is a link or not?

+6
reference php
source share
2 answers

No, the problem is that the first parameter of the function is passed by reference (this means that the function can change the argument in the caller’s area). Therefore, you must pass a variable or something that can be assigned as the first argument. When you create an array of type array($a) , it simply copies the value of the variable $a (which is 0) to the slot in the array. It does not refer to the $a variable in any way. And then when you call the function, it is as if you were doing this, which does not work:

 test(0) 

If you really want to, you can put $a in an array by reference, but it's pretty complicated:

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

As for how you would say that an array element is a reference ... it's complicated. You can do var_dump() in the array and find the "&" character:

 > var_dump($args); array(1) { [0]=> &int(1) } 
+4
source share

Check out the comments on this PHP documentation page:

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

+2
source share

All Articles