Metodi protetti in OOP in PHP

PHP supporta i metodi protetti tramite il modificatore protected. Tali metodi sono ereditati, ma non sono visibili dall'esterno della classe.

Vediamo come funziona. Scriviamo una classe genitore con un metodo protetto:

php<?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);
    }
  }
?>

Utilizziamo questo metodo protetto in una classe figlia:

php<?php
  class Student extends User {
    public function setSurn($surn) {
      $this->surn = $surn;
    }
    public function getSurn() {
      return $this->capeFirst($this->surn);
    }
  }
?>
Задание 1

Nel codice seguente, rendi il metodo helper protetto:

php<?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;
    }
  }
?>