PHP reserved keywords allowed in namespace? (public, private, default)
✔ Recommended Answer
The PHP manual hints that as of PHP 7.0.0 these keywords are allowed as property, constant, and method names of classes, interfaces and traits, except that class may not be used as constant name, which also incorporate the requested keyword public
.
List of reserved keywords, which you can't use for namespacing:
__halt_compiler
, abstract
, and
, array
, as
, break
, callable
, case
, catch
, class
, clone
, const
, continue
, declare
, default
, die
, do
, echo
, else
, elseif
, empty
, enddeclare
, endfor
, endforeach
, endif
, endswitch
, endwhile
, eval
, exit
, extends
, final
, for
, foreach
, function
, global
, goto
, if
, implements
, include
, include_once
, instanceof
, insteadof
, interface
, isset
, list
, namespace
, new
, or
, print
, private
, protected
, public
, require
, require_once
, return
, static
, switch
, throw
, trait
, try
, unset
, use
, var
, while
, xor
A potential workaround to fix this issue is to add an extra character to the word or use the plural form of the word. Another opportunity would be to go one level up in the namespace and use the keyword as a prefix PublicFooController
. (or even suffix, if you prefer that)
My intention was to scope my web app into public
(for guests and visitors) and private
(for private needs) area.I went for namespace App\Http\Controllers\Frontend
and namespace App\Http\Controllers\Backend
instead of trying to incorperate the words public
and private
in to my namespacing, even if I personally think these generally fits better to my needs, because both have frontend and backend. But... Anyway, this keeps me off having trouble organizing my files and namespaces the way I would do, when I would use public
and private
.
Source: stackoverflow.com
Answered By: MrMAG
In PHP, public
, private
, and default
are not reserved keywords, but they are considered to be language constructs. Therefore, they cannot be used as names for classes, functions, variables, or constants.
However, they can be used as part of a namespace name. So you can create a namespace with any name that contains public
, private
, or default
. For example:
phpnamespace mynamespace\public;
class MyClass {
public function myMethod() {
echo 'This is a public method';
}
}
In this example, public
is used as part of the namespace name, and MyClass
has a public method myMethod()
.
However, it is generally not recommended to use language constructs or reserved keywords in namespace names, as this can make the code less clear and may cause confusion. It is better to use more descriptive and meaningful names for namespaces.
Comments
Post a Comment