Simone Nigro Simone Nigro - 6 months ago 19
PHP Question

PHP call_user_func use reference on &$this

what is the best way (memory safe) to use

call_user_func
from self instance eg.:

call_user_func(array($this, 'method'));


or by reference, eg.:

call_user_func(array(&$this, 'method'));


PS. i know the best way is
$this->method
but for framework design pattern reason i do use
call_user_func

Answer

If I am aware, it doesn't really matter, because PHP will do the same thing in both cases: will just pass reference to the same object (the object will be not cloned). So for simplicity, I would go without &

Some test:

class test 
{ 
    function foo() {
        call_user_func([$this, 'bar']); 
        call_user_func([&$this, 'bar']);
    } 
    private function bar() {
        echo spl_object_hash($this), PHP_EOL;
    }  
}

and outputs:

php > $obj = new test();
php > $obj->foo();
0000000025077e4a0000000075174bd2
0000000025077e4a0000000075174bd2
Comments