0

I want to use variables inside class names.

For example, let's set a variable named $var to "index2". Now I want to print index2 inside a class name like this:

controller_index2, but instead of doing it manually, I can just print the var name there like this:

controller_$var;

but I assume that's a syntax error.

How can I do this?

    function __construct()
    {
        $this->_section = self::path();

        new Controller_{$this->_section};

    }
tereško
  • 58,060
  • 25
  • 98
  • 150

5 Answers5

2

It's a hideous hack, but:

php > class foo { function x_1() { echo 'success'; } };
php > $x = new foo;
php > $one = 1;
php > $x->{"x_$one"}();
          ^^^^^^^^^^^^
success

Instead of trying to build a method name on-the-fly as a string, an array of methods may be more suitable. Then you just use your variables as the array's key.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

Echo it as a string in double quotes.

echo "controller_{$var}";

Try this (based on your code in the OP):

function __construct()
{
    $this->_section = self::path();

    $controller_name = "Controller_{$this->_section}";

    $controller = new $controller_name;

}
Naftali
  • 144,921
  • 39
  • 244
  • 303
1

You can do this.... follow this syntax

function __construct()
{
    $this->_section = self::path();
    $classname = "Controller_".$this->_section;
    $instance = new $classname();

}

Another way to create an object from a string definition is to use ReflectionClass

$classname = "Controller_".$this->_section;
$reflector = new ReflectionClass($classname);

and if your class name has no constructor arguments

$obj = $reflector->newInstance();

of if you need to pass arguments to the constructor you can use either

$obj = $reflector->newInstance($arg1, $arg2);

or if you have your arguments in an array

$obj = $reflector->newInstanceArgs($argArray);
Orangepill
  • 24,500
  • 3
  • 42
  • 63
0

try this:

  $name = "controller_$var";
  echo $this->$name;
srain
  • 8,944
  • 6
  • 30
  • 42
0

just to add on the previous answers, if you're trying to declare new classes with variable names but all the construction parameters are the same and you are treating the instanced object all alike maybe you don't need different classes but just different instances of the same.

BVJ
  • 568
  • 4
  • 18