home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePHP CookbookSearch this book

7.14. Instantiating an Object Dynamically

7.14.2. Solution

Use a variable for your class name:

$language = $_REQUEST['language'];
$valid_langs = array('en_US' => 'US English', 
                     'en_GB' => 'British English', 
                     'es_US' => 'US Spanish',
                     'fr_CA' => 'Canadian French');

if (isset($valid_langs[$language]) && class_exists($language)) {
    $lang = new $language;
}

7.14.3. Discussion

Sometimes you may not know the class name you want to instantiate at runtime, but you know part of it. For instance, to provide your class hierarchy a pseudo-namespace, you may prefix a leading series of characters in front of all class names; this is why we often use pc_ to represent PHP Cookbook or PEAR uses Net_ before all Networking classes.

However, while this is legal PHP:

$class_name = 'Net_Ping';
$class = new $class_name;               // new Net_Ping

This is not:

$partial_class_name = 'Ping';
$class = new "Net_$partial_class_name"; // new Net_Ping

This, however, is okay:

$partial_class_name = 'Ping';
$class_prefix = 'Net_';

$class_name = "$class_prefix$partial_class_name";
$class = new $class_name;               // new Net_Ping

So, you can't instantiate an object when its class name is defined using variable concatenation in the same step. However, because you can use simple variable names, the solution is to preconcatenate the class name.

7.14.4. See Also

Recipe 6.5 for more on variable variables; Recipe 7.12 for more on defining a call dynamically; documentation on class_exists( ) at http://www.php.net/class-exists.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.