php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #54555 Late static binding effect for __NAMESPACE__
Submitted: 2011-04-18 09:15 UTC Modified: 2012-08-10 18:38 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: dinamic at gmail dot com Assigned:
Status: Wont fix Package: *General Issues
PHP Version: 5.3.6 OS: Linux
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: dinamic at gmail dot com
New email:
PHP Version: OS:

 

 [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"


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-08-10 18:38 UTC] nikic@php.net
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.
 [2012-08-10 18:38 UTC] nikic@php.net
-Status: Open +Status: Wont fix
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sun Aug 10 17:00:03 2025 UTC