示例:
error_reporting(E_ALL | E_STRICT);
class Test {}
$obj = new Test();
$obj->undeclared = "oops"; // I want an error here !! :(
echo $obj->algo; // oops
我在PHP 5.2.11和5.3.0上测试了它。
我不希望在我的对象中使用动态属性
在这种情况下,是否可以强制PHP引发ERROR?
是否使用__set()?
<?php
class Test {
public $bar;
public function __set($name, $value) {
throw new Exception('Cant set!');
}
}
$obj = new Test;
$obj->bar = 'foo';
$obj->foo = 'evil';
?>
对错误消息多加注意,就可以帮助自己进行编码。有以下作为你的基类设置将:
- 保护此类的使用不覆盖您的属性
- 保护变量的拼写错误(尤其是camel大小写错误)例如$this->callerID按预期返回,但$this->callerID抛出异常并防止代码错误
public function __set($name,$value) {
switch ($name) {
default:
// we don't allow any magic properties set or overwriting our properties
try {
$error = "Assignment of {$name} in " . static::class . ' not allowed because it is a magic variable or read-only property.';
throw new 'RuntimeException($error);
} catch ( 'RuntimeException $e ) {
echo 'Caught exception: ' . $e->getMessage() . PHP_EOL;
}
}
}
public function __get($name)
{
switch ($name) {
default:
// we don't allow any magic properties
try {
$error = "var {$name} is not a property of " . static::class . '.';
throw new 'RuntimeException($error);
} catch ( 'RuntimeException $e ) {
echo 'Caught exception: ' . $e->getMessage() . PHP_EOL;
}
}
return null;
}
public function __isset($name)
{
switch ($name) {
default:
return false;
}
}
对于记录:动态属性在PHP8.2(2022-12-08发布)中已被弃用。
从phpPHP8.2开始,动态设置属性将抛出一个弃用通知。在PHP 9中,它将引发一个错误。
请参阅https://www.php.net/releases/8.2/en.php#deprecate_dynamic_properties
"我不想在我的对象中使用动态属性。"我想你的意思是你不想让你的对象变量被定义?如果是这种情况,那么只需实例化所有的类变量。如果你真的担心它们是恒定的,而不是动态的,你甚至可以让它们成为静态的。
如果您试图访问一个不存在的对象变量,那么PHP将抛出一个错误。radmen建议的答案实际上是,PHP不会抛出错误,而是动态地为您创建未定义的对象变量。