If I have a string, that contains the name of an initiated class, how can I use it?
$anOjbect = new className();
...
$string = 'anObject';
Something like:
$t = access-object-by-name( $string );
Reference class from a string
Moderator: General Moderators
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Reference class from a string
A class method can return a string:
Public class properties can be accessed like any other variable:
Also, there is a __toString() method. If the object is used in a string context and a __toString() method is defined, then the return value of that method will be used.
Code: Select all
$str = 'Name is ' . $anOjbect->getName();Code: Select all
$str = 'Name is ' . $anOjbect->name;
// or
$str = "Name is {$anOjbect->name}";(#10850)
Re: Reference class from a string
Variable variables.
What's your reason for needing this?
Code: Select all
$foo = new Object();
$name = "foo";
$obj = $$name;
echo $obj->bar(); // calls $foo->bar => Object::barRe: Reference class from a string
tasairis- I have a menu class, and I'm working on a function to determine if a menu exists. Actually ran across your solution just a while ago, ended up using:
function menu_exists( $name )
{
global $$name;
return is_a( $$name, 'MENU' );
}
function menu_exists( $name )
{
global $$name;
return is_a( $$name, 'MENU' );
}
Re: Reference class from a string
Bad design. Why not
If you ever switch to a fully-OOP design, looking for global variables will break a lot of code.
Code: Select all
function menu_exists($menu) {
return is_a($menu, "MENU");
}
$obj = new Object();
$name = "obj";
$ismenu = menu_exists($$name); // do it here, not in menu_existsRe: Reference class from a string
Your functions should be variable addicts. They can't do anything without an injection.