Reference class from a string

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
Daz
Forum Newbie
Posts: 18
Joined: Thu Mar 19, 2009 2:12 am

Reference class from a string

Post 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 );
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Reference class from a string

Post 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.
(#10850)
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Reference class from a string

Post 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?
Daz
Forum Newbie
Posts: 18
Joined: Thu Mar 19, 2009 2:12 am

Re: Reference class from a string

Post 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' );
}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Reference class from a string

Post 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.
User avatar
JNettles
Forum Contributor
Posts: 228
Joined: Mon Oct 05, 2009 4:09 pm

Re: Reference class from a string

Post by JNettles »

Your functions should be variable addicts. They can't do anything without an injection.
Post Reply