Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ujwal's avatar
Level 2

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

Thanks for your help

0 likes
2 replies
benjamincrozat's avatar

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.

https://3v4l.org/rJRjZ#v8.1.8

1 like
ujwal's avatar
Level 2

@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()?

Thank you

Please or to participate in this conversation.