2016-08-15 117 views
0

在Laravel 4應用程序中,是否可以在命名空間中創建名爲Public的控制器?就像這樣:名稱爲'Public'的PHP名稱空間

<?php namespace Public; 

class MyController extends \BaseController { 

} 

這樣做可以給我一個錯誤:

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

但是,如果我命名空間更改爲PublicControllers,它工作正常。這是否意味着Public是不能用作命名空間的保留字?

+1

如果你真的嘗試過,你*可以*創建一個'Public'命名空間,但是你不得不求助於各種hackery來使它工作。 (例如,在任何你使用類名的地方,你都需要它是一個包含類名的字符串變量。)不值得。 – cHao

+1

想知道爲什麼這個問題收到2 downvotes。這是一個明確而具體的問題,接受的答案非常豐富。有什麼問題? – flyingL123

+0

有一點晚,但這裏有一個詳細的答案,哪個imo可以被鏈接:https://stackoverflow.com/a/44225572/2310637 – MrMAG

回答

6

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.

雖然命名空間沒有具體提及我們可以看看the PHP grammar,看到的命名空間預計將進行從T_STRING S按T_NS_SEPARATOR S(反斜槓)結合在一起。由於public有其自己的令牌類型(T_PUBLIC,在錯誤消息中提到),因此它不是合適的選擇。

請注意,這與Laravel無關。

+0

謝謝,我相信你是正確的,我會遠離這個命名空間的選擇,但出於好奇,「常量,類名稱,函數或方法名稱」是一個名稱空間? – flyingL123

+0

@ flyingL123,命名空間是沒有這些東西。請看我更新的答案。 – Chris

相關問題