Use an unknown class in another class

I want to use an unknown class with a variable in another class:

Example

$classandmethod = " index@show "; 
 namespace Lib\abc; use Lib\xyz; class abc{ function controller($classandmethod) { $a = explode("@", $classandmethod); use Lib\Controller\.$a[0]; } } 

But perhaps this is not true, please help everyone!

+5
source share
2 answers

The main problem is that use cannot have a variable as part of it, as it is used when parsing a file, and the variable is only available at run time.

This is an example of how you can do what you think ...

 <?php namespace Controller; ini_set('display_errors', 'On'); error_reporting(E_ALL); class Index { public function show() { echo "Showing..."; } } $classandmethod = "Controller\ Index@show "; list($className,$method) = explode("@", $classandmethod); $a= new $className(); $a->$method(); 

It displays ...

 Showing... 

Of course, you can say that all these classes must be in the Controller namespace, so the code will be changed to

 $classandmethod = " Index@show "; list($className,$method) = explode("@", $classandmethod); $className = "Controller\\".$className; $a= new $className(); $a->$method(); 
+1
source

From the manual :

The use keyword must be declared in the outermost area of ​​the file (global scope) or inside the namespace declaration

So you cannot use class in which you are trying to do this. Then, to create an instance of the class from a different namespace from the variable, rather than use ing, put the whole class with the names:

 <?php namespace G4\Lib { class A { public $a = "test"; } } namespace G4 { class B { public $a; public function __construct($class) { $class = "\\G4\\Lib\\".$class; $this->a = new $class; // here the magic } } $b = new B("A"); var_dump($b->a); // test } 

Demo

+2
source

Source: https://habr.com/ru/post/1275454/


All Articles