Home > Software engineering >  How to access a parent class properties in child class trait?
How to access a parent class properties in child class trait?

Time:07-28

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();

CodePudding user response:

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);
    }   
}
  • Related