⊗ppOpIhPtM 34 of 107 menu

Protected Methods in OOP in PHP

PHP supports protected methods using the protected modifier. Such methods are inherited but are not visible from outside the class.

Let's see how this works. Let's write a parent class with a protected method:

<?php class User { public function setName($name) { $this->name = $name; } public function getName() { return $this->capeFirst($this->name); } protected function capeFirst($str) { return ucfirst($str); } } ?>

Let's use this protected method in a child class:

<?php class Student extends User { public function setSurn($surn) { $this->surn = $surn; } public function getSurn() { return $this->capeFirst($this->surn); } } ?>

In the following code, make the helper method protected:

<?php class User { public function setName($name) { if ($this->notEmpty($name)) { $this->name = $name; } } public function getName() { return $this->name; } public function notEmpty($str) { return strlen($str) > 0; } } class Employee extends User { public function setSurn($surn) { if ($this->notEmpty($surn)) { $this->surn = $surn; } } public function getSurn() { return $this->surn; } } ?>
byenru