一、基本介绍
property_exists是PHP中一个比较常用的函数,它可以判断一个对象或类中是否存在指定的属性。
该函数的基本语法如下:
bool property_exists ( mixed $class , string $property )
其中,class表示要检查属性是否存在的对象或类,property表示要检查的属性名。
当属性存在时,返回true,不存在时返回false。
二、使用场景
1、动态访问属性
在某些情况下,我们需要动态地访问一个对象或类中的属性,比如在框架中使用模型操作数据库时,有时需要根据用户输入的条件检索不同的结果。
这时就可以使用property_exists来判断用户输入的属性是否正确存在,以避免出现错误。
$model = new Model();
if(property_exists($model, 'username')){
$model->username = $_POST['username'];
}
2、遍历属性
有时需要遍历一个对象或类中的所有属性,这时可以使用get_object_vars或类似函数取得所有属性列表,然后通过循环判断每个属性是否存在。
class Sample{
public $name;
protected $age;
private $gender;
}
$sample = new Sample();
$vars = get_object_vars($sample);
foreach ($vars as $key => $value) {
if(property_exists($sample, $key)){
echo "$key\n";
}
}
三、注意事项
1、属性名称区分大小写
使用property_exists时需要注意属性名称的大小写,如果属性名大小写不匹配,则返回false。
class Sample{
public $name;
}
$sample = new Sample();
var_dump(property_exists($sample, 'Name'));//false
2、属性必须可访问
使用property_exists时需要注意属性的访问权限,如果属性访问权限不足,则返回false。
class Sample{
private $name;
}
$sample = new Sample();
var_dump(property_exists($sample, 'name'));//false
3、属性必须存在
使用property_exists时需要注意属性必须存在,如果属性不存在,则返回false。
class Sample{
}
$sample = new Sample();
var_dump(property_exists($sample, 'name'));//false
四、结语
property_exists是一个简单实用的PHP函数,在动态访问属性和遍历属性时用处很大。
使用时需要注意属性的大小写和访问权限,以及属性必须存在。