如何为子类对象分配特征方法?

时间:2017-06-01 08:55:14

标签: php

我的问题非常简单。我有一个特质和儿童班。

trait mixVar {

public function go(){
return [];
}

}


class example extends foo { 

use mixVar;


public $var=$this->go(); //does not work

}

如何在PHP中制作这个?

2 个答案:

答案 0 :(得分:1)

您无法使用方法调用为属性指定默认值。你必须在构造函数中完成它。

class example extends foo 
{ 
    use mixVar;

    public $var;

    public function __construct()
    {
        $this->var = $this->go();
    }
}

答案 1 :(得分:0)

另一个解决方案是定义特征方法,如:

trait mixVar {

    public function go(){
        $this->var = [];    // your value here
    }

}