Page 1 of 1

Dynamic object method calls

Posted: Wed Aug 12, 2009 2:56 pm
by gilgamush
I'm trying to set up a page where methods are called dynamically.

Here is the situation - I have several objects, each with similar methods, such as "get_all()" which returns all objects within the class.

So for example I have

$users->get_all()
$photos->get_all()
$links->get_all()

defined as methods under those objects.

What I would like to do on my actual page is call one of these functions according to the selected menu. So if the menu "users" is selected I'd like to call "$users->get_all()", whereas if the menu photos is selected I'd like to call "$photos->get_all()".

I'm wondering if there is any better way to do this than with a repetitive if statement. Is there some way i can substitute in the name of the menu as part of the method call, by doing something along the lines of "$$selected_menu->get_all()". I know this is probably not right but I hope I've got the point across clearly.

Thanks in advance

Re: Dynamic object method calls

Posted: Wed Aug 12, 2009 5:59 pm
by Weirdan

Code: Select all

 
$method = 'get_all';
if (method_exists($users, $method)) {
    $users->{$method}();
}
 

Re: Dynamic object method calls

Posted: Fri Aug 14, 2009 3:58 am
by gilgamush
Hi Weirdan - thanks for the reply.

Would what you've done below also work before the "->" symbol?

So, for example:

Code: Select all

<?php 
if (method_exists($selected_menu, "get_all")) 
{    
    {$selected_menu}->get_all();
}
?>
Would that work (provided the string which is stored in $selected_menu is the name of the object class I want to use)?
I'll try it out anyway.
Thanks for your reply.
Cheers
G