Lectura de propiedades inexistentes en POO en PHP

Intentemos escribir datos en una propiedad inexistente - esto funcionará:

index.php<?php
  $test = new Test;
  
  $test->prop3 = 3; // escribamos 3
  echo $test->prop3; // mostrará 3
?>

Supongamos que no queremos permitir escribir en propiedades inexistentes. Y, en general, queremos permitir la escritura solo en las propiedades prop1 y prop2.

Esto es fácil de hacer - basta con agregar la condición correspondiente en el método __set:

Test.php<?php
  class Test
  {
    private $prop1;
    private $prop2;
    
    public function __set($property, $value)
    {
      // Escribamos la condición:
      if ($property == 'prop1' or $property == 'prop2') {
        $this->$property = $value;
      }
    }
    
    public function __get($property)
    {
      return $this->$property;
    }
  }
?>

Si hay muchas propiedades de este tipo, no es muy cómodo enumerarlas todas en la condición.

Escribamos las propiedades permitidas para escritura en un array y verifiquemos la presencia de la propiedad en este array usando la función in_array:

Test.php<?php
  class Test
  {
    private $prop1;
    private $prop2;
    
    public function __set($property, $value)
    {
      $properties = ['prop1', 'prop2']; // propiedades permitidas
      
      if (in_array($property, $properties)) {
        $this->$property = $value;
      }
    }
    
    public function __get($property)
    {
      return $this->$property;
    }
  }
?>