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
Dynamic object method calls
Moderator: General Moderators
Re: Dynamic object method calls
Code: Select all
$method = 'get_all';
if (method_exists($users, $method)) {
$users->{$method}();
}
Re: Dynamic object method calls
Hi Weirdan - thanks for the reply.
Would what you've done below also work before the "->" symbol?
So, for example:
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
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();
}
?>I'll try it out anyway.
Thanks for your reply.
Cheers
G