2

以这个类为例:

<?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));

输出如下:

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"
}

是否可以停止添加动态属性?是否可以获得类定义属性的列表?(即不是动态的,运行时添加的属性)

4

2 回答 2

5

尝试这个

public function __set($name, $value){
 throw new Exception('Not allowed');
}
于 2012-01-19T10:10:51.920 回答
1

您可以定义一个神奇的设置器来阻止定义属性:

<?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;
    }
}

要查看对象或类的属性,您可以尝试:

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

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

希望能帮助到你!

于 2012-01-19T10:15:25.270 回答