Следите за новинками
в нашем Telegram канале. Жми, чтобы подписаться:)
⊗ppOpIhPtP 35 of 107 menu
◀ ▶

Protected Properties in OOP in PHP

PHP also supports protected properties. They are also declared using the protected modifier. Such properties are inherited and accessible in child classes.

Let's create a parent class with a protected property containing age:

<?php class User { protected $age; public function setAge($age) { $this->age = $age; } public function getAge() { return $this->age; } } ?>

In the child class, let's create a method that increments the age by one:

<?php class Student extends User { public function incAge() { $this->age++; } } ?>

Rewrite the following code using a protected property:

<?php class User { private $name; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } } class Employee extends User { public function setName($name) { if (strlen($name) > 0) { $this->name = $name; } } } ?>
← →
↑
English▼
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline