0

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;
}
2
  • 1
    If you get an error, you should give the exact message. Commented Dec 28, 2011 at 10:09
  • Initialization is exactly what class constructors are for. Commented Dec 28, 2011 at 15:38

1 Answer 1

4

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.

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

1 Comment

Okey, then. If there is no other options, then Ill use __construct

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.