tags:

views:

131

answers:

3

I am trying to make a class from a member variable like this:

<?
class A{
    private $to_construct = 'B'; 
    function make_class(){
     // code to make class goes here
    }

}

class B{
    function __construct(){
     echo 'class constructed';
    }
}

$myA = new A();
$myA->make_class();
?>

I tried using:

 $myClass = new $this->to_construct();

and

$myClass = new {$this->to_construct}();

but neither worked. I ended up having to do this:

$constructor = $this->to_construct;
$myClass = new $constructor();

It seems like there should be a way to do this without storing the class name in a local variable. Am I missing something?

+3  A: 

Have you tried this?

 $myClass = new $this->to_construct;
Hooked
Thanks, I was thinking I needed to put the parenthesis to show it was a function. Is there still a way to do this without having to store the local class name if you need to pass parameters to the constructor?
Craig
It's not a function, though. I'm not sure how you would do what you need in PHP, either.
Hooked
+2  A: 

are you using PHP 4 or something? on 5.2.9, $myClass = new $this->to_construct(); works perfectly ...

in the end, it's what you have to live with, with PHP ... PHP syntax and semantics are VERY inconsistent ... for example, an array access to the result of a call is a syntax error:

function foo() {
 return array("foo","bar");
}
echo $foo()[0];

any other language could do that ... PHP can't ... sometimes, you simply need to store values into local variables ... same is true for func_get_args(), in older versions of PHP ... if you wanted to pass it to a function, you needed to store it in a local var first ...

back2dos
A: 

If I read well between the lines you are trying to do something like this. Right?

class createObject{
    function __construct($class){
     $this->$class=new $class;
    }

}

class B{
    function __construct(){
        echo 'class B constructed<br>';
    }
    function sayHi(){
        echo 'Hi I am class: '.get_class();
    }
}

class C{
    function __construct(){
        echo 'class C constructed<br>';
    }
    function sayHi(){
        echo 'Hi I am class: '.get_class();
    }
}
$wantedClass='B';
$finalObject = new createObject($wantedClass);
$finalObject->$wantedClass->sayHi();

--
Dam

dam