2

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.

Matthew Goulart
  • 2,873
  • 4
  • 28
  • 63
  • 1
    why not? array's a keyword: http://php.net/manual/en/reserved.keywords.php You'd get the same effect if you named it "Echo" or "For". – Marc B Feb 10 '16 at 19:03
  • in that list, array() is a keyword, not Array... I suppose you are right though... I give up! – Matthew Goulart Feb 10 '16 at 19:04
  • Can you use a different alias? – Progrock Feb 10 '16 at 19:05
  • Well as I said, the actual folder is called "Array" and my autoloader uses that to find the classes... – Matthew Goulart Feb 10 '16 at 19:06
  • 1
    From: https://kornel.ski/phpns 'Namespaced names are not tokens in the PHP parser (\ is a separator token), which means that use of a reserved word as any part of the namespace's “path” is a parse error.' – Progrock Feb 10 '16 at 19:11
  • The thing to understand is that twig is not a namespaced library so any attempt to use the 'use' statement will fail. The array issue is really just a diversion. Just use: $loader = new \Twig_Loader_Array() along with the standard composer autoload and you should be fine. – Cerad Feb 10 '16 at 20:26
  • I would be using the standard autoloader but at work we are completely off-line as far as our Web servers go. (we host a lot of internal Web applications) so composer is pretty useless to us. – Matthew Goulart Feb 10 '16 at 22:52

1 Answers1

3

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/"
    }
},

// ...
Community
  • 1
  • 1
chalasr
  • 12,971
  • 4
  • 40
  • 82