Is it possible to make a Class accessible in all namespaces?

2

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 the spl_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();
    }
}
    
asked by anonymous 05.08.2015 / 19:33

1 answer

0

There is nothing standard to do this other than using use or \ , however we can "cheat" php using eval within spl_autoload_register to extend the class within the namespace.

<?php
class Utils {
   public static 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)) {
        $np = explode('\', $class); //Dividi string

        //Checa se a classe já existe no namespace especifico (previnir conflitos)
        if (class_exists(implode('::', $np)) === false) {

            //Remove o nome da classe, pois usaremos apenas o namespace
            array_pop($np);

            //executa um namespace dentro do eval "copiado" (estendendo a classe Utils)
            eval(
                'namespace ' . implode('\', $np) . ' {' . PHP_EOL .
                'class Utils extends \Utils {}' . PHP_EOL .
                '}'
            );
        }

        require_once $file;
    }
});

$user = new \Controllers\Foo\User;
$user->foo(); //Irá exibir "Olá mundo!"

I admit it is a gambiarra and maybe I will not use it, but it's still a tip.

  

Note: Using use \Utils as Utils does not work within eval

    
11.08.2015 / 07:48