note 91552 added to language.namespaces.dynamic
| From: | guilhermeblanco@php.net | Date: | Tue, 16 Jun 2009 19:04:00 +0000 |
| Subject: | note 91552 added to language.namespaces.dynamic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-156940@lists.php.net to get a copy of this message | ||
Please be aware of FQCN (Full Qualified Class Name) point.
Many people will have troubles with this:
<?php
// File1.php
namespace foo;
class Bar { ... }
function factory($class) {
return new $class;
}
// File2.php
$bar = \foo\factory('Bar'); // Will try to instantiate \Bar, not \foo\Bar
?>
To fix that, and also incorpoare a 2 step namespace resolution, you can check for \ as first char of
$class, and if not present, build manually the FQCN:
<?php
// File1.php
namespace foo;
function factory($class) {
if ($class[0] != '\\') {
echo '->';
$class = '\\' . __NAMESPACE__ . '\\' . $class;
}
return new $class();
}
// File2.php
$bar = \foo\factory('Bar'); // Will correctly instantiate \foo\Bar
$bar2 = \foo\factory('\anotherfoo\Bar'); // Wil correctly instantiate \anotherfoo\Bar
?>
----
Server IP: 217.13.201.10
Probable Submitter: 201.23.78.250
----
Manual Page -- http://www.php.net/manual/en/language.namespaces.dynamic.php
Edit -- https://master.php.net/note/edit/91552
Del: integrated -- https://master.php.net/note/delete/91552/integrated
Del: useless -- https://master.php.net/note/delete/91552/useless
Del: bad code -- https://master.php.net/note/delete/91552/bad+code
Del: spam -- https://master.php.net/note/delete/91552/spam
Del: non-english -- https://master.php.net/note/delete/91552/non-english
Del: in docs -- https://master.php.net/note/delete/91552/in+docs
Del: other reasons-- https://master.php.net/note/delete/91552
Reject -- https://master.php.net/note/reject/91552
Search -- https://master.php.net/manage/user-notes.php