Page 1 of 1

call method using class object and method name as string

Posted: Tue Jul 08, 2008 8:23 am
by naresh.khokhani
Hello,

I have a class which has many methods. I have created one another php which creates an object of this class. Now I get a method name of that class from POST data. I want to call the respective method of that class using the object of that class and the method name I got from POST data.

I want something like this ::

//php class file ABC.php
class ABC
{
public function sayHi($input)
{
return "Hi " . $input;
}
public function sayHello($input)
{
return "Hello " . $input;
}
}

//another php named test.php
$obj = new ABC();

$methodName = $_REQUEST['takeAction']; //$methodName = 'sayHi' or 'sayHello'

$val = $obj->$methodName("Naresh"); //I don't know what should be here, in fact this is my question

echo "output : " . $val;


I guess this is pretty simple to understand what I want. Let me know if you know. Thanks in advance :) I know there is another way of either switch case or if-else but I don't want to make my wrapper php dependent on class file.

Regards,

Naresh

Re: call method using class object and method name as string

Posted: Tue Jul 08, 2008 9:24 am
by s.dot
I believe this will work...

Code: Select all

if (method_exists($obj, $_REQUEST['takeAction']))
{
    call_user_func(array($obj, $_REQUEST['takeAction']), 'Naresh');
}
 
But I don't know if this is the best scenario to do.

Re: call method using class object and method name as string

Posted: Thu Jul 10, 2008 12:38 am
by naresh.khokhani
Thanks scottayy,

That works very fine. I managed with following code ::

Code: Select all

if(method_exists($obj, $_REQUEST['takeAction']))
{
     $obj->$_REQUEST['takeAction']("Naresh");
}
else
{
     echo "method " . $_REQUEST['takeAction'] . " does not exists";
}
Thanks once again :)

Regards,

Naresh Khokhaneshiya
scottayy wrote:I believe this will work...

Code: Select all

if (method_exists($obj, $_REQUEST['takeAction']))
{
    call_user_func(array($obj, $_REQUEST['takeAction']), 'Naresh');
}
 
But I don't know if this is the best scenario to do.