Прыватныя метады ў ААП у PHP

Прыватнымі могуць быць не толькі ўласцівасці, але і метады. Звычайна прыватнымі робяць дапаможныя метады, каб яны выпадкова не маглі быць выкліканы звонку класа.

Давайце паглядзім на прыкладзе. Хай у нас ёсць наступны клас:

php<?php
  class User {
    private $name;
    
    public function __construct($name) {
      $this->name = $name;
    }
    
    public function show() {
      return $this->name;
    }
  }
?>

Зробім у гэтым класе прыватны метад, які параметрам будзе прымаць радок і рабіць загалоўнай яе першы сімвал:

php<?php
  class User {
    private $name;
    
    public function __construct($name) {
      $this->name = $name;
    }
    
    public function show() {
      return $this->name;
    }
    
    private function cape($str) {
      return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
    }
  }
?>

Скарыстаемся нашым дапаможным метадам унутры іншага метаду:

php<?php
  class User {
    private $name;
    
    public function __construct($name) {
      $this->name = $name;
    }
    
    public function show() {
      return $this->cape($this->name);
    }
    
    private function cape($str) {
      return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
    }
  }
?>

Давайце праверым. Створамі аб'ект нашага класа:

php<?php
  $user = new User('john');
?>

Выклічым публічны метад, які выкарыстоўвае дапаможны:

php<?php
  echo $user->show();
?>
Задание 1

У наступным кодзе зрабіце дапаможны метад прыватным:

php<?php
  class Employee {
    public function __construct($name, $salary) {
      $this->name = $name;
      $this->salary = $salary;
    }
    
    public function getSalary() {
      return $this->addSign($this->salary);
    }
    
    public function addSign($num) {
      return $num . '
;
    }
  }
?>