Skip to content
Advertisement

Private property in parent class can be accessed and re-assigned through the instance of child class in PHP but protected one can’t

I am very confused why $produk1->harga = 500; can still make a change (or re-assign the value 500) to private $harga property despite private $harga in class Produk has PRIVATE visibility ? $product1 is an instance of class Komik.

$produk1 = new Komik("Naruto", "Masashi Kishimoto", "Shonen Jump", 30000, 100);

And by echo $produk1->harga; it prints out 500 and not an ERROR. But when I change the visibility to protected $harga it prints out ERROR. How come? I don’t understand. Thank you for the answers.

JavaScript

OUTPUT =

Komik : Naruto | Masashi Kishimoto, Shonen Jump (Rp.30000) – 100 halaman. Game : Uncharted | Neil Druckmann, Sony Computer (Rp.250000) ~ 5 jam.


500

IF $harga property visibility is protected

JavaScript

OUTPUT =

Fatal error: Uncaught Error: Cannot access protected property Komik::$harga in …

Error: Cannot access protected property Komik::$harga in …

Advertisement

Answer

It’s because private properties are not inherited, and when you are trying to access your private property from child class – PHP can’t find it and dynamically creates new public one. See example below. Protected properties are inherited and that’s why you can’t access them from other parts of code.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement