Does not create a class instance from a string that contains the namespace and class name. If you do not use USE everything works, but does not want to use USE

 Рабочий вариант: <?php namespace SE_Core\Test; class Main { public function show() { } } $className = 'Main'; $class = 'SE_Core\Test\\' . $className; $obj = new $class(); print_r($obj); ?> Нерабочий вариант: <?php namespace SE_Core\Test; use SE_Core\Test as SE; class Main { public function show() { } } $className = 'Main'; $class = 'SE\\' . $className; $obj = new $class(); print_r($obj); ?> 
  • @ splash58 why is this so? use is just an alias. But in general, why use the full names found in the same namespace is the question. Yes, and do alias to the current space. Especially since this use is valid only within the framework of this file, that is, transferring it will not work anywhere. - teran
  • This I whipped up to demonstrate the mistake - quaresma89
  • @teran and without it, too, does not find - eval.in/909088 - splash58
  • Without use, it gives me information about the object, everything is fine - quaresma89
  • @ splash58 is not supposed to, when dynamically creating a full name is required. - teran

1 answer 1

It does not work, because the aliases defined using use distributed only to the current file, and most importantly, they make sense only at the stage of compiling the code, they do not exist at runtime. Therefore, it is not surprising that the class is not - no. This is not a mistake, but a feature of the language, so phn is arranged.

Documentation :

Import is performed at compile time, and does not affect the names of dynamic classes , functions, or constants.

In original:

It is not a dynamic class, function or constant names.

probably a more successful translation would be " ... and therefore does not affect ... "

Quote from the "PHP: Basics" section of the documentation

If a string ( string ) containing the class name is used with the new directive, a new instance of this class will be created. If the name is in a namespace, then it must be fully specified.

  • Of course, I didn’t quite understand the difference in the use of new SE \ Class and if I had placed SE in a string - quaresma89
  • @ quaresma89 supplemented the answer with another documentation quotation. and SE, as already written above is not available at all during the execution of the code, this is so-called. syntactic sugar available during parsing and code compilation. at the time the code is executed, php knows nothing about your SE . - teran
  • Now it is clear, thanks - quaresma89