0

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'?

3
  • Technically you don't need the ()'s to start that new class. Also, try assigning it to a variable $new_one = $one->class; $two = new $new_one(); Commented Aug 28, 2012 at 13:21
  • I would always discourage you to do anything like this. Simply because you are nto sure whether the given class has the functionality you think it has... It's a maintenance horror! Rather just create a function that creates an object based on the value of the string like function GetMeMyClass($input) { switch ($input) { case 'One': return new One(); case 'Two': return new Two(); default: die("Invalid class given in GetMeMyClass"); } } Commented Aug 28, 2012 at 13:24
  • @bkwint I wasn't after your personal preference when it comes to OOP. I just wanted a solution to the question posed. Thanks for your thoughts though. Commented Aug 28, 2012 at 13:34

1 Answer 1

9
$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

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

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.