![](/img/trans.png)
[英]How to get the value of the static properties of a child class in the parent class?
[英]How to access a parent class properties in child class trait?
我有一個擴展 Foo 的 class SpecificFoo。 SpecificFoo 具有屬性 $bar,它是 class Bar 的一個實例。 當我使用 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();
您不能通過設計,但我可能會將SpecificFoo
作為對 Bar 的引用傳遞,以保留您缺少的引用。 由於您不能在 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
}
}
現在您可以訪問 trait 中的屬性。 命名可以改變,但感覺起源是合適的。
trait Baz {
public function someMethod() {
dd($this->origin->id);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.