call method using class object and method name as string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
naresh.khokhani
Forum Newbie
Posts: 3
Joined: Tue Jul 08, 2008 7:59 am

call method using class object and method name as string

Post 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
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

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

Post 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.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
naresh.khokhani
Forum Newbie
Posts: 3
Joined: Tue Jul 08, 2008 7:59 am

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

Post 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.
Post Reply