what's the point of function &do_job()?
Moderator: General Moderators
-
global_erp_solution
- Forum Commoner
- Posts: 25
- Joined: Sun Jul 08, 2012 6:47 am
what's the point of function &do_job()?
what's the point of the superfluous ampersand in &do_job? as far as I know, PHP starting from 5 always return reference instead of value? what's the purpose of this (assuming I'm creating brand new app with 5.4 with no need for backward compat).
Re: what's the point of function &do_job()?
PHP does not return references by default for scalar values (int, float, string) and arrays so in those cases an ampersand might be useful. But yes, PHP 5+ always returns objects by reference.
You can do some pretty wicked things with references to scalar values. Checkout this article on Autoboxing in php. Scroll to the section "How does it work in practice?" and you can see this craziness:
You can do some pretty wicked things with references to scalar values. Checkout this article on Autoboxing in php. Scroll to the section "How does it work in practice?" and you can see this craziness:
Code: Select all
$y = & string("aaa");
// lets check, that $y is an object
var_dump($y);
// now we are overwritting $y variable with a scalar value of "zzz"
$y = "zzz";
// var_dump() shows us, that "zzz" is still an object, not the scalar type as in regular PHP
var_dump($y);
// the line below should raise a fatal error, because "zzz" was a scalar type (string), but it will be ok, because $y is still an object (thanks to autoboxing)
var_dump($y->toUpperCase());Re: what's the point of function &do_job()?
Interesting, but wouldn't really work if the variable in question was caught in a circular reference loop, causing destructor execution to be deferred until garbage collector kicks in, probably long after the variable was overwritten.tr0gd0rr wrote:Checkout this article on Autoboxing in php.
-
global_erp_solution
- Forum Commoner
- Posts: 25
- Joined: Sun Jul 08, 2012 6:47 am
Re: what's the point of function &do_job()?
which are valid?
I also assume that if the function returns a reference (we're talking about scalar types only now), the variable to which the returned reference is assigned must also use ampersand. Is this correct?
will work while this
won't work.
Code: Select all
function test(){
return &object;
}
Code: Select all
function &test(){
return &object;
}
Code: Select all
function &test(){
return object;
}
Code: Select all
$my_var = &test();
Code: Select all
$my_var = test();