Arthur
Arthur

Reputation: 11

Assign to variable existing class

Take this example:

class Container {
    public $text;
    public $variable2;
}

class Text {
    public $other_variable;
}

How can I assign a Text instance to Container::$variable, without using the __construct method?

In the end I want this effect:

$class = new Container();
$class->text->other_variable;

If I try the following, PHP gives me an error:

class Container {
    public $variable = new Text();
    public $variable2;
}

Upvotes: 0

Views: 96

Answers (1)

deceze
deceze

Reputation: 522402

It's not possible. You have to construct a new Text somewhere, and this cannot be done at the time the class is defined (i.e. where you tried to do it), since class values can only be initialized with static values, not expressions. You will have to do it in the constructor.

Upvotes: 4

Related Questions