namespace My\Namespace; use ExtNamespace\FloatToInt; class test { function t () { $class_a = 'FloatToInt'; $class_b = 'ExtNamespace\FloatToInt'; // $d = new FloatToInt() - работает. // $d = new $class_a() - не работает: Fatal error: Class 'FloatToInt' not found... // $d = new $class_b() - работает. } } 

Tell me how to write the class name to a variable without specifying the full path to the class and why does the creation of an object with new $ class_a () not work? Indeed, at first glance, the code in the second and third lines is identical:

 1 $class_a = 'FloatToInt'; 2 $d = new FloatToInt(); 3 $d = new $class_a(); 
  • You can create an object this way, your code simply does not see the FloatToInt class, the path ExtNamespace \ FloatToInt is correct? Does autoloading work? - cheops
  • Yes, the path is correct, the object is created without problems as follows: $ d = new FloatToInt (); but using a variable that contains the same name - the error class was not found. Moreover, if the variable is written the full path to the class: $ class_b = 'ExtNamespace \ FloatToInt'; then the $ d = new $ class_b () call also works ... - Miron

1 answer 1

Found the answer to my question, as it is not surprising, in 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.

Very strange behavior, as for me ...