Reputation: 681
Is it possible to pass a function by reference? So everytime the reference variable is called the function will be called aswell. Take a look at my code.
<?php
class Documents {
private static $docs = array(
'She went to the toilet and on her way back, opened the wrong door',
'She had found something that would mean she\'d never be poor again - but there was a catch',
'It was just for one night',
'He watched, helpless, as the door closed behind her'
);
public static function get() {
return self::$docs[array_rand(self::$docs)];
}
}
class Printer {
public static $content;
}
Printer::$content = &Documents::get();
echo Printer::$content;
echo "\n" . Printer::$content;
echo "\n" . Printer::$content;
Right now it'll print 3 similar lines but i would like it to call Documents::get()
everytime Printer::$content
is printed because Printer::$content = **&**Documents::get();
it is by reference.
Upvotes: 1
Views: 89
Reputation: 11832
You can use the magic method __get()
.
class Printer {
public function __get($name)
{
switch($name) {
case "content":
return Documents::get();
break;
default:
return $this->$name;
break;
}
}
}
But this cannot be done in static context. So you would have to have an instance of Printer. (Perhaps use a singleton?)
Upvotes: 0
Reputation: 360602
There are variable functions:
php > function foo($bar) { echo $bar; }
php > $baz = 'foo';
php > $baz('qux');
qux
But you cannot have PHP automatically execute that "referenced" function when the variable is simply accessed, e.g:
php > $baz;
php >
As you can see, the foo
function was not called, and no output was performed. Without the ()
to signify a function call, that variable is like any other - it's just a string whose contents happen to be the same as a particular functions. It's the ()
that makes the string "executable".
Note that variable functions, while useful in some limited circumstances, should be avoided as they can lead to spaghetti code and difficult-to-debug bugs.
Upvotes: 0
Reputation: 522024
No, you cannot have a variable which you treat as a variable which nonetheless runs code behind the scenes. If you write $foo
, that's using the value of a variable. Only of you write $foo()
are you explicitly executing a function.
Having said that, there are some situations in which object methods will be called implicitly. For instance, if $foo
is an object and you use it in a string context:
echo $foo;
This will (try to) implicitly call $foo->__toString()
.
Please do not get the idea to somehow abuse this implied method call to do anything fancy. If you want to call functions, call functions. You can even return functions from other functions, so there's no lack of possibility to pass around functions. You will have to call them explicitly with ()
however.
Upvotes: 3