Home  >  Article  >  Backend Development  >  Accessing Protected Parent Class Variables in PHP: Why Use `$this->bb` Over `parent::bb`?

Accessing Protected Parent Class Variables in PHP: Why Use `$this->bb` Over `parent::bb`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 21:20:29333browse

Accessing Protected Parent Class Variables in PHP: Why Use `$this->bb` Over `parent::bb`?bb` Over `parent::bb`?" />

Accessing Parent Class Variables in PHP

The provided code demonstrates an issue where a child class is unable to access the protected variable $bb inherited from its parent class. To resolve this, the variable can be accessed using the syntax $this->bb.

<code class="php">class A {
    private $aa;
    protected $bb = 'parent bb';

    function __construct($arg) {
       //do something..
    }

    private function parentmethod($arg2) {
       //do something..
    }
}

class B extends A {
    function __construct($arg) {
        parent::__construct($arg);
    }
    function childfunction() {
        echo $this->bb; // Outputs 'parent bb'
    }
}

$test = new B($some);
$test->childfunction();</code>

Using $this->bb implies that the inherited variable is now part of the current object and can be accessed like any other instance variable.

Additional Note:

While using $this->bb solves the immediate issue, it's important to understand the difference between $this-> and parent:: when accessing inherited variables and methods.

$this-> refers to the current object, while parent:: refers to the parent class. $this-> can be used to access inherited variables directly, while parent:: is used to call parent class methods or access parent class static variables.

For example, if you wanted to override a parent class method while still accessing the original method from the parent class, you could use the following syntax:

<code class="php">class Child extends Parent {
    function myMethod() {
        parent::myMethod(); // Calls the parent class's myMethod()
    }
}</code>

The above is the detailed content of Accessing Protected Parent Class Variables in PHP: Why Use `$this->bb` Over `parent::bb`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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