Proprietà protette in OOP in PHP

PHP supporta anche le proprietà protette. Anche loro vengono dichiarate con il modificatore protected. Tali proprietà vengono ereditate e sono accessibili nelle classi figlie.

Creiamo una classe genitore con una proprietà protetta che contenga l'età:

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

Nella classe figlia creiamo un metodo, che incrementa l'età di uno:

php<?php
  class Student extends User {
    public function incAge() {
      $this->age++;
    }
  }
?>
Задание 1

Riscrivi il seguente codice utilizzando una proprietà protetta:

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