Page 1 of 1

what's the point of function &do_job()?

Posted: Thu Jul 19, 2012 10:29 am
by global_erp_solution
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()?

Posted: Thu Jul 19, 2012 2:31 pm
by tr0gd0rr
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:

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()?

Posted: Thu Jul 19, 2012 7:28 pm
by Weirdan
tr0gd0rr wrote:Checkout this article on Autoboxing in php.
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.

Re: what's the point of function &do_job()?

Posted: Sat Jul 21, 2012 3:15 am
by global_erp_solution
which are valid?

Code: Select all

function test(){
    return &object;
}

Code: Select all

function &test(){
    return &object;
}

Code: Select all

function &test(){
    return object;
}
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?

Code: Select all

$my_var = &test();
will work while this

Code: Select all

$my_var = test();
won't work.