Bug #74257 [Com]: Leading slash in namespace declaration

From: Date: Thu, 16 Mar 2017 16:46:15 +0000
Subject: Bug #74257 [Com]: Leading slash in namespace declaration
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-207875@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=74257&edit=1

 ID:                 74257
 Comment by:         tpunt@php.net
 Reported by:        david at grudl dot com
 Summary:            Leading slash in namespace declaration
 Status:             Open
 Type:               Bug
 Package:            Compile Failure
 PHP Version:        7.1.2
 Block user comment: N
 Private report:     N

 New Comment:

This is not a bug, but rather a feature in namespaces known as relative names.

In short, the following line:
namespace \X;

is not a namespace *declaration*, but rather an *expression* that resolves to the symbol X of the
current namespace. The "namespace \" part (where space is optional) is either evaluated to
the currently defined namespace (it is simply ignored for the global namespace).

When utilising this feature, symbols that are not found in the current namespace will not fallback
to the globally defined functions or constants.

So, the following works:
var_dump(namespace\PHP_ZTS);

But the following will error (due to an undefined PHP_ZTS constant in the current namespace):
namespace test;
var_dump(namespace\PHP_ZTS);

Whilst obviously the following will work as expected (by falling back to the globally defined
PHP_ZTS constant):
namespace test;
var_dump(PHP_ZTS);

See the manual for further information: http://php.net/manual/en/language.namespaces.rules.php


Previous Comments:
------------------------------------------------------------------------
[2017-03-16 12:47:20] david at grudl dot com

Description:
------------
Leading slash in namespace declaration can cause silent ignorance of namespace declaration.

https://3v4l.org/DEZBT

Test script:
---------------
<?php

define('X', 'Y');

namespace \X;

class Test
{
}

echo Test::class;


Expected result:
----------------
Fatal error: Namespace declaration statement has to be the very first statement or after any declare
call in the script

Actual result:
--------------
'Test'


------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=74257&edit=1


Thread (4 messages)

« previous php.bugs (#207875) next »