如何初始化实例属性?

时间:2018-01-15 09:23:37

标签: php oop

我的班级中有示例代码:

public $themePath = "layouts/inbox/";

public $theme     = $this->themePath."theme-limitless.";

public $inboxView = $this->theme."inbox";

这里我的代码不起作用。我必须将我的主题名称保存在一个var和另一个var中的主题路径中,并使用主题名称使用视图。现在我有错误:

Constant expression contains invalid operations:

public $theme     = $this->themePath."theme-limitless."; // Error line

通常我必须在var $inboxView中获取路径:

$inboxView = "layouts/inbox/theme-limitless.inbox";

1 个答案:

答案 0 :(得分:1)

您可以在__construct方法中初始化类属性:

class MyClass
{
    public $themePath = "layouts/inbox/";
    public $theme;
    public $inboxView;

    function __construct() {
        $this->theme     = $this->themePath . "theme-limitless.";
        $this->inboxView = $this->theme . "inbox";
    }

}