VitVit
VitVit

Reputation: 113

Use unknown class in the 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 maybe it's not true, please help everyone!

Upvotes: 6

Views: 5220

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57121

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

Upvotes: 1

ishegg
ishegg

Reputation: 9927

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

Upvotes: 2

Related Questions