Can I create a PHP class that can't have properties added to it dynamically at run-time?

143 views Asked by At

Take this class for an example:

<?php

class Person
{
    private $name = null;
    private $dob = null;

    public function __construct($name, $dob)
    {
        $this->name = $name;
        $this->dob = $dob;
    }
}

$potts = new Person('Matt', '01/01/1987');
var_dump($potts);

$potts->job = 'Software Developer'; // new dynamic property
var_dump($potts);

var_dump(get_object_vars($potts));

The output is as follows:

object(Person)#1 (2) {
  ["name":"Person":private]=>
  string(4) "Matt"
  ["dob":"Person":private]=>
  string(10) "01/01/1987"
}

object(Person)#1 (3) {
  ["name":"Person":private]=>
  string(4) "Matt"
  ["dob":"Person":private]=>
  string(10) "01/01/1987"
  ["job"]=>
  string(18) "Software Developer"
}

array(1) {
  ["job"]=>
  string(18) "Software Developer"
}

Is it possible to stop dynamic properties being added? Is it possible to get a list of class-defined properties? (i.e. not dynamic, run-time added properties)

2

There are 2 answers

3
Andy Pieters On BEST ANSWER

Try this

public function __set($name, $value){
 throw new Exception('Not allowed');
}
0
capi On

You can define a magic setter which stops properties from being defined :

<?php

class Person
{
    private $name = null;
    private $dob = null;

    public function __set($name, $value) {
        //nothing here if you want nothing to happen
        //when a non-defined property is being set
        //otherwise, some error throwing
    }

    public function __construct($name, $dob)
    {
       $this->name = $name;
       $this->dob = $dob;
    }
}

For viewing properties from an object or class you can try :

http://www.php.net/manual/en/function.get-class-vars.php

http://www.php.net/manual/en/function.get-object-vars.php

Hope it helps!