note 91552 modified in language.namespaces.dynamic by danbrown
| From: | danbrown@php.net | Date: | Tue, 16 Jun 2009 19:06:09 +0000 |
| Subject: | note 91552 modified in language.namespaces.dynamic by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-156941@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 incorporate 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
?>
--was--
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
?>
http://php.net/manual/en/language.namespaces.dynamic.php