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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
global_erp_solution
Forum Commoner
Posts: 25
Joined: Sun Jul 08, 2012 6:47 am

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

Post 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).
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

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

Post 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());
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

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

Post 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.
global_erp_solution
Forum Commoner
Posts: 25
Joined: Sun Jul 08, 2012 6:47 am

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

Post 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.
Post Reply