如何创建不允许动态属性的PHP类?
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;
Run Code Online (Sandbox Code Playgroud)
拯救的神奇方法:
class User
{
public $username;
public $password;
public function __set($key, $value) {
throw new Exception('illegal'); // or just trigger_error()
}
}
Run Code Online (Sandbox Code Playgroud)