note 77991 added to function.call-user-func
| From: | interact at NOSPAM dot interactimpact dot com | Date: | Sun, 23 Sep 2007 02:38:26 +0000 |
| Subject: | note 77991 added to function.call-user-func | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-130702@lists.php.net to get a copy of this message | ||
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
----
Server IP: 208.69.120.35
Probable Submitter: 66.82.9.87
----
Manual Page -- http://www.php.net/manual/en/function.call-user-func.php
Edit -- https://master.php.net/note/edit/77991
Del: integrated -- https://master.php.net/note/delete/77991/integrated
Del: useless -- https://master.php.net/note/delete/77991/useless
Del: bad code -- https://master.php.net/note/delete/77991/bad+code
Del: spam -- https://master.php.net/note/delete/77991/spam
Del: non-english -- https://master.php.net/note/delete/77991/non-english
Del: in docs -- https://master.php.net/note/delete/77991/in+docs
Del: other reasons-- https://master.php.net/note/delete/77991
Reject -- https://master.php.net/note/reject/77991
Search -- https://master.php.net/manage/user-notes.php