简体   繁体   中英

How to access a parent class properties in child class trait?

I have a class SpecificFoo that extends Foo. SpecificFoo has property $bar which is a instance of class Bar. When i use trait Baz from SpecificFoo's Bar, how to access id of SpecificFoo?

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. Since you can't pass this as a reference at class definition, i would do a setter.

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. Naming can be change, but felt origin was fitting.

trait Baz {
    public function someMethod() {
        dd($this->origin->id);
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM