PHP-də OOP-də mövcud olmayan xassənin oxunması

Gəlin mövcud olmayan bir xassəyə məlumat yazmağa çalışaq - bu işləyəcək:

index.php<?php
  $test = new Test;
  
  $test->prop3 = 3; // 3 yazaq
  echo $test->prop3; // 3 çap edəcək
?>

Tutaq ki, mövcud olmayan xassələrə yazmağa icazə vermək istəmirik. Və, ümumiyyətlə, yalnız prop1 və prop2 xassələrinə yazılışa icazə vermək istəyirik.

Bunu etmək asandır - __set metodunda müvafiq şərti əlavə etmək kifayətdir:

Test.php<?php
  class Test
  {
    private $prop1;
    private $prop2;
    
    public function __set($property, $value)
    {
      // Şərt yazaq:
      if ($property == 'prop1' or $property == 'prop2') {
        $this->$property = $value;
      }
    }
    
    public function __get($property)
    {
      return $this->$property;
    }
  }
?>

Əgər belə xassələr çox olarsa, onların hamısını şərtdə sadəlamaq çox rahat deyil.

Gəlin yazılış üçün icazə verilən xassələri massivdə yazaq və in_array funksiyasından istifadə edərək xassənin bu massivdə olub-olmadığını yoxlayaq:

Test.php<?php
  class Test
  {
    private $prop1;
    private $prop2;
    
    public function __set($property, $value)
    {
      $properties = ['prop1', 'prop2']; // icazə verilən xassələr
      
      if (in_array($property, $properties)) {
        $this->$property = $value;
      }
    }
    
    public function __get($property)
    {
      return $this->$property;
    }
  }
?>