PHP da OOP da Privat usullar

Nafaqat xususiyatlar, balki usullar ham privat bo‘lishi mumkin. Odatda, yordamchi usullar tashqaridan chaqirilmasligi uchun ularni privat qilishadi.

Keling, bir misolni ko‘rib chiqaylik. Quyidagi klassimiz bor deb faraz qilaylik:

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

Keling, ushbu klassda satrni parametr sifatida qabul qiladigan va uning birinchi belgisini bosh harfga aylantiradigan privat metod yarataylik:

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

Keling, yordamchi metodimizdan boshqa metod ichida foydalanaylik:

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

Keling, tekshirib ko‘raylik. Klassimizning ob'ektini yaratamiz:

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

Yordamchi metoddan foydalanadigan ochiq metodni chaqiramiz:

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

Quyidagi kodda yordamchi metodni privat qiling:

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 . '
;
    }
  }
?>