我可以创建一个在运行时无法动态添加属性的PHP类吗?

Mat*_*hew 2 php oop object-properties

以此课程为例:

<?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));
Run Code Online (Sandbox Code Playgroud)

输出如下:

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"
}
Run Code Online (Sandbox Code Playgroud)

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

And*_*ers 5

试试这个

public function __set($name, $value){
 throw new Exception('Not allowed');
}
Run Code Online (Sandbox Code Playgroud)