cactusbin
cactusbin

Reputation: 681

How can I create an object inside a class?

How can I do this, as the most obvious way doesn't work:

<?php

    class Inner {

    public $var;
    }

    class Outer {

    $test = new Inner;
    }

?>

Yields:

Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in /f5/debate/public/test.php on line 10

Upvotes: 0

Views: 371

Answers (1)

Brenton Alker
Brenton Alker

Reputation: 9072

In PHP you can't instantiate a class as a default value of a property. You need to do it in a function (in this case, probably likely the constructor). eg.

class Inner {
    public $var;
}

class Outer {
    public $test;

    public function __construct() {
        $this->test = new Inner();
    }
}

Upvotes: 4

Related Questions