PHP: How to access a namespace class with :: instead of \?
-
02-06-2021 - |
Question
I use namespace
for a class like this below,
class_tidy.php,
namespace foo;
class tidy {
public function hello() {
echo 'Hello';
}
}
index.php,
class MyAutoloader
{
public static function load($className)
{
$parts = explode('\\', $className);
require 'classes/class_'.end($parts) . '.php';
}
}
spl_autoload_register("\MyAutoloader::load");
$test = new foo\tidy();
$test->hello();
It works perfectly, but I wonder if I can access the class, instead of,
$test = new foo\tidy();
But,
$test = new foo::tidy();
Which looks prettier. but with this error,
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$' ...
Solution
You can't. The PHP syntax uses \
for namespaces.
As a matter of fact, php uses the T_PAAMAYIM_NEKUDOTAYIM (which is their name for the double colon) for only one thing, using it after a class name to specify you want a member of that class.
I do believe there are some obscure details in the way this works which prevented PHP from using it as the namespace sperator as well, but I do not know which. (The thing is that this would mean that even if you branched from the official php and made your own version, you would have to go through a lot of work just to get that slight syntax change you want.)
OTHER TIPS
The php team choose \ as the namespace separator. Even if you think :: is better you cannot change it. May I ask you why you would that?
Read the official manual: http://php.net/language.namespaces.nested
::
is not supported as namespace separator, because it's already used (and therefore reserved) as scope resolution operator
Foo::$bar;
Also interesting: The corresponding RFC https://wiki.php.net/rfc/namespaceseparator