Home > Backend Development > PHP Tutorial > How to Access Protected Parent Class Variables in PHP Subclasses?

How to Access Protected Parent Class Variables in PHP Subclasses?

Patricia Arquette
Release: 2024-10-23 00:44:03
Original
366 people have browsed it

How to Access Protected Parent Class Variables in PHP Subclasses?

Accessing Parent Class Variables in PHP

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template