Page 1 of 1
Reference class from a string
Posted: Sun Jan 24, 2010 9:36 pm
by Daz
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 );
Re: Reference class from a string
Posted: Mon Jan 25, 2010 2:15 am
by Christopher
A class method can return a string:
Code: Select all
$str = 'Name is ' . $anOjbect->getName();
Public class properties can be accessed like any other variable:
Code: Select all
$str = 'Name is ' . $anOjbect->name;
// or
$str = "Name is {$anOjbect->name}";
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.
Re: Reference class from a string
Posted: Mon Jan 25, 2010 3:00 am
by requinix
Variable variables.
Code: Select all
$foo = new Object();
$name = "foo";
$obj = $$name;
echo $obj->bar(); // calls $foo->bar => Object::bar
What's your reason for needing this?
Re: Reference class from a string
Posted: Mon Jan 25, 2010 11:03 am
by Daz
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' );
}
Re: Reference class from a string
Posted: Mon Jan 25, 2010 12:13 pm
by requinix
Bad design. Why not
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_exists
If you ever switch to a fully-OOP design, looking for global variables will break a lot of code.
Re: Reference class from a string
Posted: Mon Jan 25, 2010 12:32 pm
by JNettles
Your functions should be variable addicts. They can't do anything without an injection.