Haozhuo Huang Haozhuo Huang - 3 months ago 7
PHP Question

"this" in class inheritance, PHP

I am new to PHP and got two questions. When I tried the following code:

<?php
class Base{
public function getId(){
return $this->id;
}
};


class Derived extends Base{
public $id = 1;

public function id(){
return $this->id;
}

};


$d1 = new Derived();

echo $d1->id();//echo 1
echo $d1->getId();//echo 1
?>


The code above would echo two 1's.

However, when I tried the following code:

<?php
class Base{
public function getId(){
return $this->id;
}
};


class Derived extends Base{
private $id = 1;
public function id(){
return $this->id;
}
};

$d1 = new Derived();

echo $d1->id();//echo 1
echo $d1->getId();//Cannot access private property Derived::$id
?>


The second function call will give me an error "Cannot access private property Derived::$id". So my question is what is $this in Base referred to when I made $d1->getId()?

I am quite confused in that if $this refers to the d1 instance, then it should be able to access the private $id. However, if $this refers to the Base inside $d1, then how can it get the $id property from Derived class? Thanks!

Answer

So my question is what is $this in Base referred to when I made $d1->getId()?

$this is an instance of the instantiated object that was created with the new keyword of whatever class - it's not the class itself, it's an instance of that class. In your case, because you created $d1 with new Derived(), $this is an instance of Derived. Base doesn't have access to Derived's private property because base private properties are exclusive to the class that defined them. They do not share with inherited classes.

how can it get the $id property from Derived class?

You're looking for protected visibility:

<?php
class Base{
    public function getId(){
        return $this->id;
    }
};


class Derived extends Base{
    protected $id = 1;
    public function id(){
        return $this->id;
    }
};

$d1 = new Derived();

echo $d1->id();
echo $d1->getId();
?>

Protected visibility shares with other classes that are inherited with it.

However expecting a property to exist on a derived class is bad practice. You cannot guarantee that the derived class specifies that property. You might consider defining the base as abstract and checking for its existence.

Comments