6

In a Laravel 4 application, is it possible to create a controller in namespace called Public? 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 PublicControllers, it works fine. Does that means Public is a reserved word that can't be used as a namespace?

flyingL123
  • 7,686
  • 11
  • 66
  • 135
  • 1
    You *can* create a `Public` namespace, if you really try, but you'd have to resort to all kinds of hackery to make it work. (Everywhere you use a class name, for example, you'd need it to be a string variable containing the class name.) Wouldn't be worth it. – cHao Aug 15 '16 at 19:17
  • 3
    Would love to know why this question received 2 downvotes. It's a clear, specific question and the accepted answer is very informative. What's the issue? – flyingL123 Aug 15 '16 at 20:22
  • A little bit late, but here is a detailed answer, which imo schould be linkedr: https://stackoverflow.com/a/44225572/2310637 – MrMAG May 29 '17 at 06:05

1 Answers1

15

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.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257