简体   繁体   English

如何在类内创建对象?

[英]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

In PHP you can't instantiate a class as a default value of a property. 在PHP中,您无法将类实例化为属性的默认值。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM