0

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?

0

3 Answers 3

3

Have you tried this?

 $myClass = new $this->to_construct;
Sign up to request clarification or add additional context in comments.

2 Comments

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?
It's not a function, though. I'm not sure how you would do what you need in PHP, either.
2

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 but 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.

Comments

0

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

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.