Recipe 7.22. Instantiating an Object Dynamically

7.22.1. Problem

You want to instantiate an object, but you don't know the name of the class until your code is executed. For example, you want to localize your site by creating an object belonging to a specific language. However, until the page is requested, you don't know which language to select.

7.22.2. Solution

Use a variable for your class name:

$language = $_REQUEST['language']; $valid_langs = array('en_US' => 'US English',                      'en_UK' => 'British English',                      'es_US' => 'US Spanish',                      'fr_CA' => 'Canadian French'); if (isset($valid_langs[$language]) && class_exists($language)) {     $lang = new $language; }

7.22.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 pseudonamespace, 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.22.4. See Also

Documentation on class_exists( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: