note 77991 deleted from function.call-user-func by nlopess

From: Date: Sun, 23 Sep 2007 21:15:08 +0000
Subject: note 77991 deleted from function.call-user-func by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-130720@lists.php.net to get a copy of this message
Note Submitter: interact at NOSPAM dot interactimpact dot com ---- I am looking for a way to make dynamic method calls on objects. I may have overlooked other posts but here is the example anyway. <?php class MyClass1 { var $input1 = 4; var $input2 = 5; function MyClass1(){} function adding() { $var1 = $this->input1; $var2 = $this->input2; $result = $var1 + $var2; return $result; } } class MyClass2 { var $anotherObject; function MyClass2($anotherObject){ $this->anotherObject = &$anotherObject; } } ?> Now we will call a method of object of object: <?php $myclass1Object =& New MyClass1(); $myclass2Object =& New MyClass2(&$myclass1Object); $output = $myclass2Object->anotherObject->adding(); echo $output; //outputs 9 if all is well ?> Now we want to do it dynamically that works in PHP 4 and 5. There are two ways of doing this. First Method using variable variables: <?php $objectName = 'myclass2Object'; //case sensitive. $anotherObject = 'anotherObject';//case sensitive $functionName = 'adding'; $output = $$objectName->{$anotherObject}->{$functionName}(); echo $output; //will output 9 as well ?> Now the same using call_user_func(): <?php $output = call_user_func(array(&$$objectName->{$anotherObject},$functionName)); echo $output; //outputs 9 as well ?> If you have a method of an object of an object that requires parameters you can do this: <?php call_user_func(array(&$objectName->{$anotherObject},$functionName), $arg1, $arg2); ?> I hope this might be helpful to someone. Cheers. Chris

« previous php.notes (#130720) next »