Variable functions within an object
| From: | Julio Sergio Santana | Date: | Thu, 29 Jul 2004 22:11:50 +0000 |
| Subject: | Variable functions within an object | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-192249@lists.php.net to get a copy of this message | ||
I need to record the names of functions, and then use them later.
Recently I found the following example within the on-line documentation:
<?php
function foo() {
echo "In foo()<br />\n";
}
$func = 'foo';
$func(); // This calls foo()?> then I supposed that it was easy to extend this concept to objects and wrote the following case: <?php function foo() { echo "In foo()<br />\n"; } class a { var $fname; function a() {
$this->fname = 'foo'; // the name of the function} function execute() { // method to execute the named function
$this->fname();
// I also tried here
// {$this->fname}();
// ${this->fname}();
// "$this->fname"();
// but none of these worked
}
}
$w = new a;
$w->execute();
?>
And this was the error I got:
X-Powered-By: PHP/4.1.2
Content-type: text/html
<br>
<b>Fatal error</b>: Call to undefined function: fname() in <b>-</b> on line <b>14</b><br>
I know that this can be solved easily with an intermediate variable:
$temp = $this->fname;
$temp();
but I wonder if there is a more direct method.