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};

    }
1
  • You can't declare a class with a variable name. Commented Jul 17, 2013 at 14:58

5 Answers 5

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.

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

Comments

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;

}

2 Comments

No problem @JunatanmDegraded :-D
I get one error now Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\framework\includes\class\Core.class.php on line 28
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);

Comments

0

try this:

  $name = "controller_$var";
  echo $this->$name;

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.