如何验证属性是否可以在PHP中访问?

时间:2016-03-21 10:28:57

标签: php class object methods properties

对于包含私有属性的类,property_exists()函数返回true(php> 5.3)。对于函数,有一个is_callable方法,它不仅确认方法存在,而且还可用(作为method_exists()的替代方法)。是否有与此函数等效的对应函数来确认此属性是否可访问?

<?php

class testClass {

    private $locked;

    public $unlocked;

    private function hiddenFunction(){
        return "hidden";
    }

    public function visibleFunction(){
        return "visible";
    }

}

$object = new testClass();

var_dump(property_exists($object, "unlocked")); // returns true
var_dump(property_exists($object, "locked")); // returns true > php 5.3

var_dump(method_exists($object, "hiddenFunction")); // returns true but can't be called
var_dump(method_exists($object, "visibleFunction")); // returns true

var_dump(is_callable(array($object, "hiddenFunction"))); // returns false
var_dump(is_callable(array($object, "visibleFunction"))); // returns true

?> 

1 个答案:

答案 0 :(得分:0)

您可以使用Reflection类taht让您逆向工程类,接口,函数,方法和扩展

例如,要获取类的所有公共属性,可以执行以下操作:

$reflectionObject    = new ReflectionObject($object);
$testClassProperties = $reflectionObject->getProperties(ReflectionProperty::IS_PUBLIC);
print_r ($testClassProperties);

<强>输出

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => unlocked
            [class] => testClass
        )

)

获取类的所有公共方法,您可以执行以下操作:

$reflectionObject    = new ReflectionObject($object);
$testClassProperties = $reflectionObject->getMethods(ReflectionProperty::IS_PUBLIC);
print_r ($testClassProperties);

<强>输出

Array
(
    [0] => ReflectionMethod Object
        (
            [name] => visibleFunction
            [class] => testClass
        )

)