PHPにおけるOOPのプライベートメソッド

プライベートにできるのはプロパティだけではなく、 メソッドも同様です。通常、プライベートにするのは ヘルパーメソッドで、これによりクラスの外部から 誤って呼び出されることを防ぎます。

例を見てみましょう。 次のようなクラスがあるとします:

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