6

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 maybe it's not true, please help everyone!

1
  • Why do you want to use a class during parsetime/runtime? I dont see any reason to do so. Commented Feb 19, 2018 at 13:32

2 Answers 2

2

From the manual:

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations

So you can't use a class where you're trying to do it. Then, to instantiate a class from a different namespace from a variable, rather than useing it, supply the whole namespaced class:

<?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's the magic } } $b = new B("A"); var_dump($b->a); // test } 

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much
It's no problem, man. Any further questions don't hesitate to ask.
1

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

This is an example of how you can do what you seem to be after...

<?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(); 

This displays...

Showing... 

You could of course say that all of these classes must be in the Controller namespace and so the code will change to

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.