Reputation: 1128
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
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