How to access a parent class properties in child class trait?
Note: Edited to include simple use case.
In the code below, is there any way I can access $id of SpecificFoo in trait Baz's someMethod() ?
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();
Here's a simplified version of what you're asking (please do it yourself next time, you'll get your answer much faster). 😊
<?php
class Foo
{
use Bar;
public string $id = 'foo';
}
trait Bar
{
public function someMethod()
{
var_dump($this->id); // string(3) "foo"
}
}
(new Foo)->someMethod();
As you can see, it works. And you can even run the code on the link below.
@benjamincrozat Hi, Thanks for your reply. But A simplified version of my question would need three classes and a trait.
Here is simplified version.
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();
Here how can i access id of SpecificFoo in someMethod()?