Reputation: 2248
OK, this has been a personal bugbear of mine for quite some time. Say I have a class.
class One {
public $class = 'Two';
public $member = 'member';
}
class Two {
public $member = 'Hey there';
function __construct() {
print 'Created';
}
}
$one = new One();
// case 1: works
$two_class = $one->class;
$two = new $two_class();
// case 2: fails
$two = new {$one->class}();
Is there any way to instantiate a class from a class memeber without first assigning the name to a variable? I die a little inside every time I want to create a class dynamically from a property, and I have to populate a variable first. Can anyone explain to me technically why this doesn't work when:
print $two->{$one->method}
Will happily print 'Hey there'?
Upvotes: 0
Views: 288
Reputation: 16915
$two = new $one->class();
Demo: http://codepad.org/64iCiWn2
But you gonna get big trouble if $one->class()
is function - it may be confusing, but same thing will happen if if $two_class
become function
Upvotes: 9