Emanuil Rusev
Emanuil Rusev

Reputation: 35235

Value Objects in PHP

How do I create a PHP class that allows no 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;

Upvotes: 4

Views: 135

Answers (2)

planestepper
planestepper

Reputation: 3297

You can check constraining php dynamic properties. The idea is to specify which properties do exist and can be modified on an array, and then validate whether the property being updated (as in Alix's answer, example expanded below) is part of that 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);
    }
}

Upvotes: 0

Alix Axel
Alix Axel

Reputation: 154533

Magic methods to the rescue:

class User
{
  public $username;
  public $password;

  public function __set($key, $value) {
    throw new Exception('illegal'); // or just trigger_error()
  }
}

Upvotes: 7

Related Questions