Dynamic object method calls

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
gilgamush
Forum Newbie
Posts: 4
Joined: Wed Aug 05, 2009 5:54 pm

Dynamic object method calls

Post 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
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Dynamic object method calls

Post by Weirdan »

Code: Select all

 
$method = 'get_all';
if (method_exists($users, $method)) {
    $users->{$method}();
}
 
gilgamush
Forum Newbie
Posts: 4
Joined: Wed Aug 05, 2009 5:54 pm

Re: Dynamic object method calls

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