note 109230 added to language.variables.variable

From: Date: Thu, 28 Jun 2012 01:58:13 +0000
Subject: note 109230 added to language.variables.variable
Groups: php.notes 
Request: Send a blank email to php-notes+get-188950@lists.php.net to get a copy of this message
Variable Class Instantiation with Namespace Gotcha: Say you have a class you'd like to instantiate via a variable (with a string value of the Class name) <?php class Foo { public function __construct() { echo "I'm a real class!" . PHP_EOL; } } $class = 'Foo'; $instance = new $class; ?> The above works fine UNLESS you are in a (defined) namespace. Then you must provide the full namespaced identifier of the class as shown below. This is the case EVEN THOUGH the instancing happens in the same namespace. Instancing a class normally (not through a variable) does not require the namespace. This seems to establish the pattern that if you are using an namespace and you have a class name in a string, you must provide the namespace with the class for the PHP engine to correctly resolve (other cases: class_exists(), interface_exists(), etc.) <?php namespace MyNamespace; class Foo { public function __construct() { echo "I'm a real class!" . PHP_EOL; } } $class = 'MyNamespace\Foo'; $instance = new $class; ?> ---- Server IP: 69.147.83.197 Probable Submitter: 24.6.36.242 ---- Manual Page -- http://www.php.net/manual/en/language.variables.variable.php Edit -- https://master.php.net/note/edit/109230 Del: integrated -- https://master.php.net/note/delete/109230/integrated Del: useless -- https://master.php.net/note/delete/109230/useless Del: bad code -- https://master.php.net/note/delete/109230/bad+code Del: spam -- https://master.php.net/note/delete/109230/spam Del: non-english -- https://master.php.net/note/delete/109230/non-english Del: in docs -- https://master.php.net/note/delete/109230/in+docs Del: other reasons-- https://master.php.net/note/delete/109230 Reject -- https://master.php.net/note/reject/109230 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188950) next »