I am trying to understand the visibility rules for methods and properties in PHP when using traits and abstract classes. I noticed some behaviors that I would like to clarify:
- Abstract Classes:
- I defined a public method and property in an abstract class and tried to override them in a child class. I got an error when trying to change the visibility from public to private for the method, which stated that I cannot change public to private. However, changing from private to public was allowed for the method.
- The same behavior was observed for properties. Changing the visibility from public to private for a property in a child class resulted in an error, but changing from private to public was allowed.
- Traits:
- When using traits, I know that you can change the visibility of methods using the as keyword. However, when overriding methods directly in the class using the trait, I was able to change the visibility from public to private and vice versa.
- For properties defined in the trait, I was not able to change the visibility when overriding them in the class. Attempting to change a public property to private in the class using the trait resulted in an error.
I am aware of the Less Restrictive Visibility rule, but I am trying to understand why these differences exist between abstract classes and traits in PHP. Specifically:
- Why can methods have their visibility changed in traits but not in abstract classes when overriding?
- Why can properties not have their visibility changed in traits while methods can?
abstract class AbstractClass {
public function publicMethod() {}
private function privateMethod() {}
public $publicProperty;
private $privateProperty;
}
class ChildClass extends AbstractClass {
// Error
private function publicMethod() {}
// Allowed
public function privateMethod() {}
// Error
private $publicProperty;
// Allowed
public $privateProperty;
}
trait MyTrait {
public function publicMethod() {}
private function privateMethod() {}
public $publicProperty;
private $privateProperty;
}
class MyClass {
use MyTrait;
// Allowed
private function publicMethod() {}
// Allowed
public function privateMethod() {}
// Error
private $publicProperty;
// Error
public $privateProperty;
}
New contributor
S.kh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.