Matthew Goulart
Matthew Goulart

Reputation: 3065

Using the word "array" in a "use" statement in PHP

I have the following:

use Twig\Loader\Array as Twig_Loader_Array;

I am hoping to use TWIG in my custom framework, and my autoloader isn't quite smart enough to load twig stuff, so I have to help it out.

Only problem is, the above line spits out:

Parse error: syntax error, unexpected 'Array' (T_ARRAY), expecting identifier (T_STRING) in... 

Uhhhh.. What?

Is it really thinking that the ...\Array bit is trying to create an array???

How can I get around this? I can't change folder names because i'll break twig if I do.

Upvotes: 2

Views: 376

Answers (1)

chalasr
chalasr

Reputation: 13167

You cannot use a reserved keyword as part of your namespace.

Also, array or Array make no difference. PHP is case insensitive for its keywords (same for conditions, method names, class names , ...).

See PHP reserved words as namespaces and class names

Plus, the Twig_Loader_Array doesn't have any namespace.
The only thing you have to do is use it like new \Twig_Loader_Array(/* ... */)

For more informations, see the Twig API

To get around this problem, just use composer to manage your vendors and register your app in the autoload part of your composer.json.

Example :

// composer.json

// ...

"autoload": {
    "psr-0": {
        "YourNamespace\\YourLib": "src/"
    }
},

// ...

Upvotes: 3

Related Questions