Till
Till

Reputation: 1128

PHP: Instantiating class by object property value

Is there no way to instantiate a new class instance using the value of an object property?

$arg = 'hello';
$class = $foo->bar;
$instance = new $class($arg);

This works fine, but I'd like to skip the 2nd line and just do something like:

$instance = new {$foo->bar}($arg);

Upvotes: 0

Views: 63

Answers (1)

Amacado
Amacado

Reputation: 617

In PHP 5.0.4+ this works fine:

$instance = new $foo->bar($arg);

Full example:

<?php
$foo = new foo();
$arg = 'hello';
$class = $foo->bar;
$instance = new $class($arg);
$instance = new $foo->bar($arg); // your requested shorthand

class foo {
    public $bar = 'bar';
}

class bar {
    public function __construct($arg) {
        echo $arg;
    }
}

see this working example.

Upvotes: 1

Related Questions