note 104762 added to language.namespaces.dynamic
| From: | AlexanderKirk at osu1 dot php dot net | Date: | Wed, 06 Jul 2011 07:57:08 +0000 |
| Subject: | note 104762 added to language.namespaces.dynamic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-181272@lists.php.net to get a copy of this message | ||
When extending a class from another namespace that should instantiate a class from within the
current namespace, you need to pass on the namespace.
<?php // File1.php
namespace foo;
class A {
public function factory() {
return new C;
}
}
class C {
public function tell() {
echo "foo";
}
}
?>
<?php // File2.php
namespace bar;
class B extends \foo\A {}
class C {
public function tell() {
echo "bar";
}
}
?>
<?php
include "File1.php";
include "File2.php";
$b = new bar\B;
$c = $b->factory();
$c->tell(); // "foo" but you want "bar"
?>
You need to do it like this:
When extending a class from another namespace that should instantiate a class from within the
current namespace, you need to pass on the namespace.
<?php // File1.php
namespace foo;
class A {
protected $namespace = __NAMESPACE__;
public function factory() {
$c = $this->namespace . '\C';
return new $c;
}
}
class C {
public function tell() {
echo "foo";
}
}
?>
<?php // File2.php
namespace bar;
class B extends \foo\A {
protected $namespace = __NAMESPACE__;
}
class C {
public function tell() {
echo "bar";
}
}
?>
<?php
include "File1.php";
include "File2.php";
$b = new bar\B;
$c = $b->factory();
$c->tell(); // "bar"
?>
(it seems that the namespace-backslashes are stripped from the source code in the preview, maybe it
works in the main view. If not: fooA was written as \foo\A and barB as bar\B)
----
Server IP: 69.147.83.197
Probable Submitter: 62.178.190.13
----
Manual Page -- http://www.php.net/manual/en/language.namespaces.dynamic.php
Edit -- https://master.php.net/note/edit/104762
Del: integrated -- https://master.php.net/note/delete/104762/integrated
Del: useless -- https://master.php.net/note/delete/104762/useless
Del: bad code -- https://master.php.net/note/delete/104762/bad+code
Del: spam -- https://master.php.net/note/delete/104762/spam
Del: non-english -- https://master.php.net/note/delete/104762/non-english
Del: in docs -- https://master.php.net/note/delete/104762/in+docs
Del: other reasons-- https://master.php.net/note/delete/104762
Reject -- https://master.php.net/note/reject/104762
Search -- https://master.php.net/manage/user-notes.php