php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #49046 namespaces with leading \ misbehave
Submitted: 2009-07-24 11:26 UTC Modified: 2009-07-24 16:58 UTC
From: simon at stienen dot name Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3SVN-2009-07-24 (SVN) OS: FreeBSD
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: simon at stienen dot name
New email:
PHP Version: OS:

 

 [2009-07-24 11:26 UTC] simon at stienen dot name
Description:
------------
So much wrong here ...

The initial intention was to get back into global namespace using the "namespace X;" syntax. (Why isn't this possible? Neither as namespace; namespace \; ... not even namespace \\;)

Curiously, "namespace \" expected the name of a constant.
Even more curiously, "namespace \foo" is looking for the constant "foo" in the *current* namespace.
If the constant exists, the namespace directive is simply ignored.
If it does not, the script dies with a fatal error.

Reproduce code:
---------------
namespace Foo;
const Bar = "Blob";

namespace \Bar;
function x() { echo __NAMESPACE__; }
x();


Expected result:
----------------
Pretty much everything else than the actual result ... but at least "Bar" or "Blob"

Actual result:
--------------
Foo

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-07-24 13:18 UTC] simon at stienen dot name
Whyever this is necessary:

<?php
namespace Foo;
const Bar = "Blob";

namespace \Bar;
function x() { echo __NAMESPACE__; }
x();
?>

... happy now?)
 [2009-07-24 16:46 UTC] cellog@php.net
the code below is looking for the Bar constant in the current namespace,

see http://us3.php.net/manual/en/language.namespaces.nsconstants.php
 [2009-07-24 16:47 UTC] cellog@php.net
note that there is some dissent amongst developers about the usefulness of the "namespace" operator, so this may go bye-bye in a future PHP 5.3.x, in which case this bug will re-open
 [2009-07-24 16:58 UTC] cellog@php.net
more to the point, here are 2 scripts that do what you want it to do:

<?php
namespace Foo;
const Bar = "Blob";

namespace Bar;
function x() { echo __NAMESPACE__; }
x(); // echoes "Bar"
?>

<?php
namespace Foo {
const Bar = "Blob";
}
namespace Bar {
function x() { echo __NAMESPACE__; }
x(); // echoes "Bar"
}
?>

and to go to global namespace, there is only one way:

<?php
namespace Foo {
const Bar = "Blob";
}
namespace {
function x() { echo __NAMESPACE__; }
x(); // echoes nothing
}
?>

 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 17 14:04:04 2025 UTC