Re: Dynamic method calling
| From: | Justin Patrin | Date: | Wed, 07 Apr 2004 23:11:25 +0000 |
| Subject: | Re: Dynamic method calling | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-182745@lists.php.net to get a copy of this message | ||
Darren Beale wrote:
Hi I'm trying to dynamically choose and call a method from within a class but actually calling a method dynamically does not seem to work whatever I try using php 4.3.3 Hopefully this test script will illustrate my point better, I always get to the "I know we get to here" bit, but there is no other output. Is what I want to achieve possible? regs Darren <?php class foo {$$ is only for use when you're doing a regular var. In other cases you just add a $. For instance, when accessing a member var, you use: $this->a; To access a dynamic one you use: $a = 'nameOfVar'; $this->$a; For member fuctions: $a = 'nameOfMemberFunction'; $this->$a(); For functions: $a = 'nameOfFunction'; $a(); -- paperCrane <Justin Patrin>var $lookup; function foo() { $this->lookup = array(); }function getItem($entry) { if (!array_key_exists($entry, $this->lookup)) { print "I know we get to here\r\n"; // random attempts at calling the relevant // method $this->{"_foo_" . $entry . "()"}; $this->{"_foo_" . $entry}; $this->${"_foo_" . $entry . "()"}; $foo = "_foo_" . $entry . "()"; $this->$$foo; $foo = "_foo_" . $entry; $this->$$foo; } return $this->lookup[$entry]; }function _foo_bar() { print "bar\r\n"; $bar = 1; $this->lookup["bar"] = $bar; unset($bar); }function _foo_bar2() { print "bar2\r\n"; $bar2 = 2; $this->lookup["bar2"] = $bar2; unset($bar2); }} $foo = new foo(); print $foo->getItem("bar2"); ?>