Robert
Robert

Reputation: 10380

php namespaces falling back to global using variable not working

I have two files:

index.php

$a = "a";

namespace.php

namespace tom\anderson\s;
include 'index.php';


echo \$a;

This does not work and outputs this error message: Parse error: syntax error, unexpected '$a' (T_VARIABLE), expecting identifier (T_STRING) in...

Why is this? Any references to official documentation would help!

Upvotes: 1

Views: 308

Answers (2)

Michael Chudinov
Michael Chudinov

Reputation: 2958

Variables do no belong to a namespace and exist in the global scope. To get program work slash before $a must be removed.

From php documentation. Defining namespaces Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants. http://php.net/manual/en/language.namespaces.definition.php

Upvotes: 0

Marcio Mazzucato
Marcio Mazzucato

Reputation: 9295

From PHP docs:

PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.

As you are using to group variables, the error is being triggered.

Upvotes: 1

Related Questions