flyingL123 flyingL123 - 1 year ago 80
PHP Question

PHP namespace called 'Public'

In a Laravel 4 application, is it possible to create a controller in namespace called

? Like this:

<?php namespace Public;

class MyController extends \BaseController {


Doing this gives me an error:

syntax error, unexpected 'Public' (T_PUBLIC), expecting identifier
(T_STRING) or \ (T_NS_SEPARATOR) or '{'

However, if I change the namespace to
, it works fine. Does that means
is a reserved word that can't be used as a namespace?

Answer Source

public is a reserved word in PHP:

These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on - but they're not, really: they are language constructs. You cannot use any of the following words as constants, class names, function or method names. Using them as variable names is generally OK, but could lead to confusion.

While namespaces aren't specifically mentioned here we can look at the PHP grammar and see that namespaces are expected to be made from T_STRINGs joined together by T_NS_SEPARATORs (backslashes). Since public has its own token type (T_PUBLIC, which is mentioned in your error message) it is not an appropriate choice.

Note that this has nothing to do with Laravel.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download