PHPのOOPにおける存在しないプロパティの読み取り

存在しないプロパティにデータを書き込んでみましょう - これは機能します:

index.php<?php
  $test = new Test;
  
  $test->prop3 = 3; // 3を書き込みます
  echo $test->prop3; // 3を出力します
?>

存在しないプロパティへの書き込みを許可したくないとします。 そして、一般的に、プロパティ prop1 と prop2 への書き込みのみを許可したいとします。

これは簡単にできます - メソッド __set に 対応する条件を追加するだけで十分です:

Test.php<?php
  class Test
  {
    private $prop1;
    private $prop2;
    
    public function __set($property, $value)
    {
      // 条件を書きます:
      if ($property == 'prop1' or $property == 'prop2') {
        $this->$property = $value;
      }
    }
    
    public function __get($property)
    {
      return $this->$property;
    }
  }
?>

このようなプロパティが多数ある場合、それらをすべて 条件で列挙するのはあまり便利ではありません。

書き込みを許可するプロパティを配列に記録し、 関数 in_array を使用して この配列内にプロパティが存在するかどうかを 確認しましょう:

Test.php<?php
  class Test
  {
    private $prop1;
    private $prop2;
    
    public function __set($property, $value)
    {
      $properties = ['prop1', 'prop2']; // 許可されたプロパティ
      
      if (in_array($property, $properties)) {
        $this->$property = $value;
      }
    }
    
    public function __get($property)
    {
      return $this->$property;
    }
  }
?>