|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-04-18 09:15 UTC] dinamic at gmail dot com
Description:
------------
I've been chilling around with the latest PHP features and noticed that there is
something missing - there is no way to get the current namespace if inheriting
some implementation, which limit us on some implementations.
For example, we have an abstract class in one namespace and adapter for the very
same class in another namespace. If we try to use the __NAMESPACE__ within the
abstract class, it uses its own one and not the one of the inheriting class. I've
checked the documentation to find some notes on this one to no avail.
Test script:
---------------
<?php
namespace SomeNamespace {
abstract class SomeAdapterAbstract {
public function getNamespace() {
return __NAMESPACE__;
}
}
}
namespace SomeNamespace\Adapters {
use \SomeNamespace\SomeAdapterAbstract;
class SomeAdapter extends SomeAdapterAbstract {};
$adapter = new SomeAdapter;
var_dump($adapter->getNamespace());
}
Expected result:
----------------
nikola@nikola-pc:~$ php test2.php
string(13) "SomeNamespace\Adapters"
Actual result:
--------------
nikola@nikola-pc:~$ php test2.php
string(13) "SomeNamespace"
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Dec 03 22:00:01 2025 UTC |
The __FOO__ style constants are compile-time scalars. They don't resolve at runtime and also don't have any kind of late binding behavior. E.g. if you use __CLASS__ it will also be the class name of the class it occurred in, not the name of some inheriting class. Instead you could for example get the namespace using (new ReflectionClass($this))->getNamespaceName() In static code (without $this) you could also use get_called_class and take everything until the last slash.