property_exists 方法的实验
bool property_exists ( mixed $class
, string $property
)
该方法是(PHP 5 >= 5.1.0, PHP 7) 的 新方法,主要作用是判断类或对象中的属性是否存在(可以无视属性权限),返回值是bool变量,存在是为true,不存在是false。
其中$class 可是字符串或类。
相关实践代码
class Obj{
public $is_public;
protected $is_protected;
private $is_private;
public static $is_public_static;
const is_const=3;
}
$obj = new Obj();
var_dump(property_exists('Obj','is_public')); //true;
var_dump(property_exists($obj,'is_public')); //true;
var_dump(property_exists($obj,'is_protected')); //true;
var_dump(property_exists($obj,'is_private')); //true;
var_dump(property_exists($obj,'is_public1')); //false;
var_dump(property_exists($obj,'is_public_static')); //true;
var_dump(property_exists('Obj','is_const')); //false;
个人感悟:该方法对const变量无法判断,并且对类的信息隐藏是一种破坏, 不过在框架中使用的很多。
PHP官方文档链接:http://php.net/manual/en/function.property-exists.php