The question is similar to this Instantiate class outside the namespace and has a good answer link
However I would like to do this automatically. For example:
Is it possible to make a Class accessible in all namespaces? Without using \
or use \Classe as Class;
.
For example, I'm using spl_autoload_register
in index.php :
<?php
class Utils {
public function example() {
echo 'Olá mundo!';
}
}
spl_autoload_register(function($class)
{
$relative_class = strtolower(str_replace('\', '/', $class));
$file = './src/' . $relative_class . '.php';
if (is_file($file)) {
require_once $file;
}
});
$user = new \Controllers\Foo\User;
user.php:
<?php
namespace Controllers/Foo;
class User
{
public function foo() {
//Something...
}
}
If I need to use the Utils class I will have to add in user.php something like:
public function foo() {
\Utils::example();
}
or
<?php
namespace Controllers/Foo;
use \Utils as Utils;
class User
{
public function foo() {
Utils::example();
}
}
- Is it possible to make the Utils class accessible to all namespaces?
- Or when I load a class with
new \Controllers\Foo\User;
is thespl_autoload_register
class automatically added to the current namespace?
I want to use the Utils class without having to add Utils
or without needing use \Utils as Utils;
( backslash
), is it possible?
Only the Utils class, I would like to use this:
<?php
namespace Controllers/Foo;
class User
{
public function foo() {
Utils::example();
}
}