I need to recursivly echo comments and their respective children from a Jelly collection in Kohana. I was wondering how I pass a variable to a function via reference. I assume it would be something like this:
function recursive(&$array)
{
recursive(&$array);
}
But I am not quite sure. So is this correct or when I call the function do I not need the ampersand?
Thanks.
You don't need the ampersand when you call the function because you have already declared it to accept a reference as a parameter using the ampersand.
So you would just write this:
function recursive(&$array)
{
recursive($array);
}
On a side note, generally you should avoid adding the ampersand to function calls. That is called call-time pass-by-reference. It's bad because the function may be expecting a parameter to be passed by value, but you're passing a reference instead so in a way you're screwing with the function without it knowing. As I have said above, a function will invariably take a parameter by reference if you declare it as such. That therefore makes call-time pass-by-reference unnecessary.
In PHP 5.3.0 and newer, call-time pass-by-reference causes PHP to emit E_DEPRECATED warnings as it has been deprecated (rightfully so).
Related
In PHP, objects are effectively passed by reference (what’s going on under the hood is a bit more complicated). Meanwhile, parameters to call_user_func() not passed by reference.
So what happens with a piece of code like this?
class Example {
function RunEvent($event) {
if (isset($this->events[$event])) {
foreach ($this->events[$event] as $k => $v) {
//call_user_func($v, &$this);
// The above line is working code on PHP 5.3.3, but
// throws a parse error on PHP 5.5.3.
call_user_func($v, $this);
}
}
}
}
$e = new Example;
$e->events['example'][] = 'with_ref';
$e->events['example'][] = 'without_ref';
$e->RunEvent('example');
function with_ref(&$e) {
$e->with_ref = true;
}
function without_ref($e) {
$e->without_ref = true;
}
header('Content-Type: text/plain');
print_r($e);
Output:
Example Object
(
[events] => Array
(
[example] => Array
(
[0] => with_ref
[1] => without_ref
)
)
[without_ref] => 1
)
Note: Adding error_reporting(E_ALL); or error_reporting(-1); to the top of the file makes no difference. I’m seeing no errors or warnings, and of course php -l on the command line shows no errors.
I was actually expecting it to work both with and without references in the callback functions. I thought that removing the ampersand before $this in call_user_func() would be enough to fix this for the latest version of PHP. Obviously, the version with the reference doesn’t work, but equally it doesn’t throw any linting errors, so it’s hard to track down such situations (which may occur many times in the codebase I’m working with).
I’ve got a practical question here: Is there any way to make the with_ref() function work? I’d like to modify only the RunEvent() code, not every single function which uses it (the majority of which do use references).
I’ve also got a curiosity question, as the behaviour I see here makes no sense to me. The opposite would make more sense. What’s actually going on here? It seems startlingly counter-intuitive that a function call without an ampersand can modify the object, while one with the ampersand cannot.
Parameters passing
The main issue is - that parameters, passed to call_user_func() will be passed as values - so they will be copy of actual data. This behavior overrides the fact, that
objects are passed by reference. Note:
Note that the parameters for call_user_func() are not passed by
reference.
Tracking error
You're not fully correct about "silent agreement" in such cases. You will see error with level E_WARNING in such cases:
Warning: Parameter 1 to with_ref() expected to be a reference, value given in
So - you will be able to figure out that you're mixing reference and values passing
Fixing the issue
Fortunately, it's not too hard to avoid this problem. Simply create reference to desired value:
class Example {
function RunEvent($event) {
if (isset($this->events[$event])) {
foreach ($this->events[$event] as $k => $v) {
$obj = &$this;
call_user_func($v, $obj);
}
}
}
}
-then result will be quite as expected:
object(Example)#1 (3) {
["events"]=>
array(1) {
["example"]=>
array(2) {
[0]=>
string(8) "with_ref"
[1]=>
string(11) "without_ref"
}
}
["with_ref"]=>
bool(true)
["without_ref"]=>
bool(true)
}
Obviously, the version with the reference doesn’t work, but equally it doesn’t throw any linting errors, so it’s hard to track down such situations (which may occur many times in the codebase I’m working with).
It throws an error: Warning: Parameter 1 to with_ref() expected to be a reference....
Error_reporting while developing should be error_reporting(-1);.
I’ve got a practical question here: Is there any way to make the with_ref() function work? I’d like to modify only the RunEvent() code, not every single function which uses it (the majority of which do use references).
You can replace call_user_func($v, $this); with $v($this);.
I’ve also got a curiosity question, as the behaviour I see here makes no sense to me. The opposite would make more sense. What’s actually going on here?
call_user_func can only pass parameters by value, not by reference.
Why does the error "expected to be a reference, value given" appear?
Here’s the modified code (taken from the accepted answer) and comment (taken from the other answers and a comment on the accepted answer). The answer to part 2 of this question is buried in a comment on the accepted answer. If the whole answer were in one place I’d just accept it and have done with it, but since I’ve stitched it together I’m throwing it in here.
function RunEvent($event) {
if (isset($this->events[$event])) {
foreach ($this->events[$event] as $v) {
$obj = &$this;
call_user_func($v, $obj);
// The user func *should* receive the object by value, not
// by reference. What's *actually* passed is a pointer to
// the location of the object, so modifications to the object
// in that func will actually be applied to the real object.
// In that case, a simple call_user_func($v, $this) will
// work.
//
// However, some of the existing user funcs receive the
// object by reference. That can and should be changed,
// but there are quite a lot to track down, and they don't
// throw linting errors. In that case, call_user_func will
// pass by value, and they're expecting to recive it by
// reference, so you get a run-time warning. (In theory,
// anyway. When I was practising on a standalone script
// I saw no warnings at all.) That's not good.
//
// One way around this would be to use $v($this) instead
// of call_user_func, but the user func may sometimes be
// a class method, so that's not going to work either. Instead,
// the above compromise method seems to work without problems.
//
// We may at some future point switch to call_user_func($v, $this),
// and track down the remaining warnings as we hit them.
//
// https://stackoverflow.com/q/20683779/209139
}
}
}
First of all, "objects" are not "passed by reference" or "effectively passed by reference" (that's a made-up term). "Objects" are not values in PHP5, and cannot be "passed" at all. The value of $e, $this, etc., is a pointer to an object.
In PHP, things are passed by reference when there is a &, and passed by value otherwise. Always.
call_by_func is just a function. In its declaration, its parameter does not have a &. Therefore, that parameter is pass-by-value. Therefore, what you passed to call_by_func is always passed by value.
You were using "call-time pass-by-reference" in PHP 5.3, which overrode a pass-by-value parameter into pass-by-reference, and was really bad practice and was removed in PHP 5.4.
Neither the functions with_ref and without_ref assign to their parameter ($e), so actually there was no point to pass it by reference. But since you declared the parameter to with_ref as pass-by-reference, there is a problem when using it with call_user_func, because as we discussed before, call_user_func takes its parameter by value, so it already lost the "reference", so there's no way it can pass-by-reference to your function. The documentation of call_user_func says it results in a warning and the call returns FALSE.
One solution, of course, it just to use $v($this);. i.e. not use call_user_func at all -- just use the name to call it directly. There is rarely a need to use call_user_func anyway.
If you must use the call_user_func* family of functions, you can use call_user_func_array with an array with elements that are by reference (Remember that you can put references into an array). That preserves the "reference" so that it can be passed to the pass-by-reference function:
call_user_func_array($v, array(&$this));
Note: Before PHP 5.4, this used to do call-time pass-by-reference. However, since PHP 5.4, this is not a call-time pass-by-reference. When we use it to call by reference a function that was meant to be called by reference, it works. When we use it to call a pass-by-value function, it works as pass-by-value.
While working with Laravel framework, more specific - Form macros, I stumbled upon a weird error.
At first, I thought it's something wrong with Laravel, but then I took everything out of context:
<?php
// placeholder function that takes variable as reference
$function = function(&$reference)
{
// append to variable
$reference = $reference . ':' . __METHOD__;
};
// test with straight call
$variable = 'something';
$function($variable);
echo $variable;
// test with call_user_func(), that gets called in Laravels case
$variable = 'something'; // reset
call_user_func($function, $variable);
echo $variable;
While the first call to $function executes properly, the second try with call_user_func(), produces (excerpt from Codepad):
Warning: Parameter 1 to {closure}() expected to be a reference, value given
PHP Warning: Parameter 1 to {closure}() expected to be a reference, value given
Fiddle: Codepad # Viper-7
While writing this, I thought about call_user_func_array(): fiddle here, but the same error is produced.
Have I got something wrong about references or is this a bug with PHP?
I would call this a bug with PHP, although it's technically a bug with call_user_func. The documentation does mention this, but perhaps not in a very enlightening way:
Note that the parameters for call_user_func() are not passed by
reference.
It would be perhaps clearer to say that the arguments to call_user_func() are not passed by reference (but note that technically it's not necessary to say anything at all; this information is also embedded in the function signature).
In any case, this means is that when call_user_func finally gets to invoking its target callable, the ZVAL (PHP engine internal data structure for all types of values) for the argument being passed is not marked as "being-a-reference"; the closure checks this at runtime and complains because its signature says that the argument must be a reference.
In PHP < 5.4.0 it is possible to work around this by using call-time pass by reference:
call_user_func($function, &$variable);
but this produces an E_DEPRECATED warning because call-time pass by reference is a deprecated feature, and will flat out cause a fatal error in PHP 5.4 because the feature has been removed completely.
Conclusion: there is no good way to use call_user_func in this manner.
This works:
call_user_func_array($function, array(&$variable));
I used this code
<?php
$myfunction = function &($arg=3)
{
$arg = $arg * 2;
return $arg;
};
echo $myfunction();
?>
Worked like a charm. :)
What happens if you do this?
call_user_func($function, &$variable);
I have a couple of libraries that use code similar to the following one.
$args = array_merge(array(&$target, $context), $args);
$result = call_user_func_array($callback, $args);
The code is different in both the cases, but the code I shown is what essentially is done. The $callback function uses the following signature:
function callback(&$target, $context);
Both the libraries document that, and third-party code (call it plug-in, or extension) adopts that function signature, which means none of the extensions defines the callback as, e.g., function my_extension_loader_callback($target, $context).
What confuses me are the following sentence in the documentation for call_user_func_array().
Before PHP 5.4, referenced variables in param_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference does not emit a deprecation notice, but it is nonetheless deprecated, and has been removed in PHP 5.4. Furthermore, this does not apply to internal functions, for which the function signature is honored. Passing by value when the function expects a parameter by reference results in a warning and having call_user_func() return FALSE.
In particular, the highlighted sentence seems to suggest that is not done for functions define in PHP code.
Does using call_user_func_array() in this way work in PHP 5.4?
When using call_user_func_array, passing by value when a function expects a reference is considered an error, in newer versions of PHP.
This was valid PHP code before PHP 5.3.3:
//first param is pass by reference:
my_function(&$strName){
}
//passing by value, not by reference, is now incorrect if passing by reference is expected:
call_user_func_array("my_function", array($strSomething));
//correct usage
call_user_func_array("my_function", array(&$strSomething));
The above pass by value is no longer possible without a warning (my project is also set to throw exceptions on any kind of error (notice, warning, etc).) so I had to fix this.
Solution
I've hit this problem and this is how I solved it (I have a small RPC server, so there is no such thing as referenced values after deserializing params):
//generic utility function for this kind of situations
function &array_make_references(&$arrSomething)
{
$arrAllValuesReferencesToOriginalValues=array();
foreach($arrSomething as $mxKey=>&$mxValue)
$arrAllValuesReferencesToOriginalValues[$mxKey]=&$mxValue;
return $arrAllValuesReferencesToOriginalValues;
}
Although $strSomething is not passed by reference, array_make_references will make it a reference to itself:
call_user_func_array("my_function", array_make_references(array($strSomething)));
I think the PHP guys were thinking of helping people catch incorrectly called functions (a well concealed pitfall), which happens often when going through call_user_func_array.
If call_user_func_array() returns false you have a problem, otherwise everything should be fine.
Parameters aren't passed by reference by default anymore, but you do it explicitly.
The only trouble could be that your reference gets lost during array_merge(), haven't tested that.
I've found this same problem when upgrading to PHP5.4 when there were several sites using call_user_func_array with arguments passed by reference.
The workaround I've made is very simple and consists on replacing the call_user_func_array itself with the full function call using eval(). It's not the most elegant solution but it fits the purpose for me :)
Here's the old code:
call_user_func_array($target, &$arguments);
Which I replace with:
$my_arguments = '';
for ($i=0; $i<count($arguments); $i++) {
if ($i > 0) { $my_arguments.= ", "; }
$my_arguments.= "\$arguments[$i]";
}
$evalthis = " $target ( $my_arguments );";
eval($evalthis);
Hope this helps!
Considering that PHP has already deprecated a few functions and functionallitys, I would like to refactory my codes to fit it on php 5.3.
now, I have to eliminate all the 'Call-time pass-by-reference' . So, I have three questions:
1 - If I replace:
$myclass->myfunc(&$myvar);
by
$myvar = $myclass->myfunc($myvar);
will work ?
2 - what do I do if I have something like that?
$myclass->myfunc(&$myVar, &$ourvar);
3 - How about
$x = &new myclass();
Thanks for your time, any help will be very appreciated
First, are you familiar with what call-time pass by reverence is? Normal pass by reference is accomplished by the function declaring that certain arguments are pass by reference by prepending a & to the parameter in its declaration.
Call-time pass by reference means that the function is declared to take those arguments by value, and you are changing its behavior to pass-by-reference after the fact. Call-time pass by reference shouldn't really ever be necessary. Every function should have a specific purpose, and to correctly accomplish its purpose, it should either always take an argument by reference, or always take it by value. It is bad to make a function do something it was not designed to do.
Responding to your questions about $myclass->myfunc(&$myvar); and $myclass->myfunc(&$myVar, &$ourvar); I would say that, if you need to pass by reference to that function, then it should be declared as always pass by reference. i.e.
function myfunc(&$x, &$y) { ... }
Then to use it you just call it without the &
$myclass->myfunc($myVar, $ourvar);
$x = &new myclass(); is completely irrelevant. You are not passing anything. It is still valid syntax.
function do_sth_with_var($variable) {
if (is_by_reference($variable)) {
$variable = something($variable)
}
else {
return something($variable);
}
}
so for example if 'something' was strtoupper:
do_sth_with_var(&$str); // would make $str uppercase, but
$str = do_sth_with_var($str); // that way should it be done if ommitting that '&'
Disclaimer: This does not directly answer the OP's question, but I'm providing this answer in the hope that it will help him/her.
I'd say, provide a consistent interface. Declare the function parameter as reference:
function do_sth_with_var(&$variable) {
and it will always be a reference.
You could also to the contrary and always copy the value:
function do_sth_with_var($variable) {
$val = $variable;
// work with $val here
return $val;
}
No built-in PHP function I know changes its behaviour based on whether you pass a reference or not. They are clearly defined to either treat an argument as reference or not and I would argue that users are used to this clear definitions and can deal with them.
For example, sort always sorts an array in place. You know that. So if you want to keep the original, you make a copy before the call.
It depends on your function whether it makes sense to perform an in-place operation or not. E.g. it makes sense for sort but I'd say it does not make sense for string processing.
Also, as you are using PHP 5.3, passing variables by reference at call-time is deprecated:
As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.
So you (or whoever) should not do that anyway.
calltime-pass-by-ref is considered deprecated as of 5.3.
apart from that ... answering the question academically; I don't think there is any way to determine that propperly, b/c there is no difference between a "reference" and a usual parameter. In PHP every variable is a pointer to section in the symbol table. A reference just makes another variable point to the same section.
in PHP there are no references as C knows them for example. every variable is a pointer and every "reference" too.
PS: #Gordon: I forgot about the Reflection-Classes. Of course, they work on a meta-level. My answer is more directed at how PHP actually deals with paramters and variables.
This topic is covered very well by the first comment here (official php manual)
to answer your question literally, you can try experimenting with debug_zval_dump. Refcounts will be different for by val and by reference parameters.
function xxx($a) {
debug_zval_dump($a);
}
$b = 123;
xxx($b); // long(123) refcount(4)
xxx(&$b); // long(123) refcount(1)
In your specific case you don't need to know if the value is passed by reference or not you can do something like:
function do_sth_with_var($variable) {
$variable = something($variable)
return $variable;
}
It should do exactly what you ask in your question
I don't know any good and safe way to control that a passed parameter is a reference and not just a value inside the body of a function at running time.