Value Objects in PHP

How to create a PHP class that does not allow dynamic properties?

class User { public $username; public $password; } $user = new User; $user->username = "bill.gates"; // This is a dynamic property and I need setting it to be considered illegal. $user->something = 123; 
+4
source share
2 answers

Magic methods to help:

 class User { public $username; public $password; public function __set($key, $value) { throw new Exception('illegal'); // or just trigger_error() } } 
+7
source

You can check php dynamic property constraint . The idea is to indicate which properties exist and can be changed in the array, and then check if the updated property (as in Alix's answer, the example expanded below) is part of this permission list.

 class User { public $username; public $password; private $non_dynamic_props = array('username','password'); public function __set($key, $value) { if($this->check_legal_assignment($key)) $this->$$key = $value; else throw new Exception('illegal'); // or just trigger_error() } private function check_legal_assignment($prop){ return in_array($prop, $this->non_dynamic_props); } } 
0
source

All Articles