Importing variable namespaces

后端 未结 2 1864
时光取名叫无心
时光取名叫无心 2021-01-06 17:28

Would it be possible to import namespaces using a variable like this:

$namespace = \'User\\Authorization\\Certificate\';
use $namespace;

Ob

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 17:59

    While it isn't possible to pass a namespace in a variable to use, you can place the namespace and the expected "short" class name in a variable and use that in most places where you'd need it, like invoking new.

    $namespace = '\foo\bar';
    $class = 'baz';
    $fully_qualified = $namespace . '\\'. $class; // \foo\bar\baz
    $a_foo_bar_baz = new $fully_qualified(...);
    var_dump( $a_foo_bar_baz instanceof $fully_qualified ); // true
    

提交回复
热议问题