note 112942 added to language.namespaces.dynamic
| From: | akhoondi+php at gmail dot com | Date: | Fri, 09 Aug 2013 16:17:23 +0000 |
| Subject: | note 112942 added to language.namespaces.dynamic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195924@lists.php.net to get a copy of this message | ||
It might make it more clear if said this way:
One must note that when using a dynamic class name, function name or constant name, the
"current namespace", as in http://www.php.net/manual/en/language.namespaces.basics.php
is global namespace.
One situation that dynamic class names are used is in 'factory' pattern. Thus, add the
desired namespace of your target class before the variable name.
namespaced.php
<?php
// namespaced.php
namespace Mypackage;
class Foo {
public function factory($name, $global = FALSE)
{
if ($global)
$class = $name;
else
$class = 'Mypackage\\' . $name;
return new $class;
}
}
class A {
function __construct()
{
echo __METHOD__ . "<br />\n";
}
}
class B {
function __construct()
{
echo __METHOD__ . "<br />\n";
}
}
?>
global.php
<?php
// global.php
class A {
function __construct()
{
echo __METHOD__;
}
}
?>
index.php
<?php
// index.php
namespace Mypackage;
include('namespaced.php');
include('global.php');
$foo = new Foo();
$a = $foo->factory('A'); // Mypackage\A::__construct
$b = $foo->factory('B'); // Mypackage\B::__construct
$a2 = $foo->factory('A',TRUE); // A::__construct
$b2 = $foo->factory('B',TRUE); // Will produce : Fatal error: Class 'B' not
found in ...namespaced.php on line ...
?>
----
Server IP: 69.147.83.199
Probable Submitter: 69.70.197.10
----
Manual Page -- http://php.net/manual/en/language.namespaces.dynamic.php
Edit -- https://master.php.net/note/edit/112942
Del: integrated -- https://master.php.net/note/delete/112942/integrated
Del: useless -- https://master.php.net/note/delete/112942/useless
Del: bad code -- https://master.php.net/note/delete/112942/bad+code
Del: spam -- https://master.php.net/note/delete/112942/spam
Del: non-english -- https://master.php.net/note/delete/112942/non-english
Del: in docs -- https://master.php.net/note/delete/112942/in+docs
Del: other reasons-- https://master.php.net/note/delete/112942
Reject -- https://master.php.net/note/reject/112942
Search -- https://master.php.net/manage/user-notes.php