Documenting strange include behaviour
[email protected] ("Robert Stoll")
| Newsgroups | php.standards |
|---|---|
| Message-ID | <[email protected]> |
Heya,
I came across a strange behaviour when a file with a namespace is included in another file which has defined a namespace
as well. Consider the following:
index.php
-------------
<?php
namespace test;
include 'include.php';
var_dump($var, const1, const2);
foo();
?>
include.php
--------------
<?php
namespace foo;
const const1 = 1;
define('const2', 3);
function foo(){
global $var;
var_dump(__NAMESPACE__);
$var = 'hi';
}
foo();
?>
The output looks as follows:
string(3) "foo"
<br />
<b>Notice</b>: Use of undefined constant const1 - assumed 'const1' in <b>C:\xampp2\htdocs\test\index.php</b> on line
<b>4</b><br />
string(2) "hi"
string(6) "const1"
int(3)
<br />
<b>Fatal error</b>: Call to undefined function test\foo() in <b>C:\xampp2\htdocs\test\index.php</b> on line <b>5</b><br
/>
Seems pretty inconsistent to me. I think we need to document this behaviour in the spec. The spec mentions "Using the
series-of-constants example, an include file called Positions.php might define the constants TOP, BOTTOM, LEFT, and
RIGHT, in their own namespace (§§),"
I interpreted that "in the same namespace" implies that they would remain in their own namespace even after inclusion.
From the example above we can see that variables and constants defined with define() do not remain in their namespace
(constants defined with const do - because the compiler substitutes them I guess). Even more strange is the fact that on
one hand the function foo remains in the namespace foo but when using global $var inside this function - which seems to
be in namespace foo, see statement var_dump(__NAMESPACE__); (is substituted by the compiler as well, so it is
misleading) - it seems that it refers to $var in test (I suppose that is not true, it refers to $var in foo but $foo is,
due to the include, available in test as well).
Another paragraph in the spec "It is important to understand that unlike the C/C++ (or similar) preprocessor, script
inclusion in PHP is not a text substitution process. That is, the contents of an included file are not treated as if
they directly replaced the inclusion operation source in the including file."
This description is by far to wage IMO and we should be more specific. I did not start to write a first draft yet
because the behaviour seems so strange to me that I wanted first some comments. Is this behaviour really how it should
be? (I should probably ask this question on internals but all other stuff relates to standards IMO).
Thoughts?
Cheers,
Robert