Zaštićene metode u OOP u PHP-u
PHP podržava zaštićene metode
pomoću modifikatora protected.
Takve metode se nasleđuju, ali nisu vidljive
spolja iz klase.
Pogledajmo kako ovo funkcioniše. Napišimo roditeljsku klasu sa zaštićenom metodom:
<?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);
}
}
?>
Iskoristimo ovu zaštićenu metodu u klasi potomku:
<?php
class Student extends User {
public function setSurn($surn) {
$this->surn = $surn;
}
public function getSurn() {
return $this->capeFirst($this->surn);
}
}
?>
U sledećem kodu napravite pomoćnu metodu zaštićenom:
<?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;
}
}
?>