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 ‘$’ …
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.)