In object-oriented programming, child classes inherit the properties and methods of their parent classes. However, accessing parent class variables directly within the child class can sometimes present challenges.
Consider the following code snippet where class B extends class A:
Question:
Why does the line echo parent::$bb; result in a fatal error? How can we access the parent variable $bb in the child class?
Answer:
The error occurs because $bb is a protected property of class A, and protected properties cannot be accessed directly from outside the class or subclasses using the parent:: syntax. Instead, we can access $bb using the following syntax:
Explanation:
The $this keyword refers to the current object. Since $bb is inherited by class B and becomes a part of the current object, we can access it using $this. This syntax effectively accesses the inherited variable as if it were a property of the child class.
Additional Information on parent::
The parent:: syntax is used to access methods or properties of the parent class from within the child class. It is typically used when you want to override a method from the parent class or add extra functionality to it.
For example, consider the following code:
In this case, the __construct() method of the Bomber class overrides the parent's __construct() method, but still makes use of it to initialize the pilot property.
The above is the detailed content of How to Access Protected Parent Class Variables in PHP Subclasses?. For more information, please follow other related articles on the PHP Chinese website!