【发布时间】:2018-04-26 11:10:10
【问题描述】:
看看以下特征:
trait PrimaryModelRest {
use RestController;
protected $primaryModel;
public function __construct() {
$mc = $this->getPrimaryModelClass();
try {
$this->primaryModel = new $mc();
if(!($this->primaryModel instanceof Model)) {
throw new ClassNotFoundException("Primary Model fatal exception: The given Class is not an instance of Illuminate\Database\Eloquent\Model");
}
} catch (Exception $e) {
throw new WrongImplementationException("Primary Model Exception: Class not found.");
}
}
/**
* @return string: Classname of the primary model.
*/
public abstract function getPrimaryModelClass();
// various functions here
}
如您所见,该 trait 确保 using 类拥有某个模型实例并实现某些方法。 只要实现类不覆盖构造函数,此方法就可以工作。
所以这是我的问题:我想确保调用构造函数或更好的解决方案,以便我可以在初始化时实例化此模型。
请回答多重继承以及多级继承。
【问题讨论】:
-
final public function __construct()防止实现类覆盖构造函数? -
很好,但是如果实现类无论如何都应该有一个构造函数,并且确保也调用了 trait 构造函数呢?
-
那么你必须“相信”实现类调用特征构造函数;如果您允许实现类拥有自己的构造函数,则无法在代码中强制执行它
-
为什么不在 getter 中实例化属性
primaryModel呢?public function getPrimaryModel() { if ($this->primaryModel === null) { ...} return $this->primaryModel; } -
标签: php inheritance constructor traits