[英]How to access a parent class properties in child class trait?
I have a class SpecificFoo that extends Foo.我有一个扩展 Foo 的 class SpecificFoo。 SpecificFoo has property $bar which is a instance of class Bar.
SpecificFoo 具有属性 $bar,它是 class Bar 的一个实例。 When i use trait Baz from SpecificFoo's Bar, how to access id of SpecificFoo?
当我使用 SpecificFoo 的 Bar 中的 trait Baz 时,如何访问 SpecificFoo 的 id?
class Foo {
public $id;
public $bar;
}
class SpecificFoo extends Foo{
public $id = 'specific';
public $bar = new Bar();
}
class Bar {
use Baz;
}
trait Baz {
public function someMethod() {
dd($this->id); //need the id of SpecificFoo here
}
}
(new SpecificFoo())->bar->someMethod();
You can't by design, but i would probably pass the SpecificFoo
as a reference to Bar, to keep that reference you are missing.您不能通过设计,但我可能会将
SpecificFoo
作为对 Bar 的引用传递,以保留您缺少的引用。 Since you can't pass this as a reference at class definition, i would do a setter.由于您不能在 class 定义中将其作为参考传递,因此我会做一个设置器。
class SpecificFoo extends Foo{
public $id = 'specific';
public $bar;
public function setBar()
{
$this->bar = new Bar($this);
}
}
class Bar {
protected $origin;
public function __construct($origin)
{
$this->origin = $origin
}
}
Now you can access the property in your trait.现在您可以访问 trait 中的属性。 Naming can be change, but felt origin was fitting.
命名可以改变,但感觉起源是合适的。
trait Baz {
public function someMethod() {
dd($this->origin->id);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.