Private metoder i OOP i PHP

Ikke kun egenskaber, men også metoder kan være private. Normalt gøres hjælpemetoder private, så de ikke ved en fejl kan kaldes udefra klassen.

Lad os se på et eksempel. Antag, at vi har følgende klasse:

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

Lad os lave en privat metode i denne klasse, som tager en streng som parameter og gør dens første tegn stort:

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

Lad os bruge vores hjælpemetode inden i en anden metode:

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

Lad os teste. Lad os oprette et objekt af vores klasse:

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

Lad os kalde den offentlige metode, der bruger hjælpemetoden:

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

Gør hjælpemetoden privat i følgende kode:

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