代码之家  ›  专栏  ›  技术社区  ›  Joe

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

  •  3
  • Joe  · 技术社区  · 9 年前

    对于包含私有属性的类,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 回复  |  直到 9 年前
        1
  •  1
  •   Halayem Anis    9 年前

    您可以使用 Reflection 这堂课会让你 反向工程类、接口、函数、方法和扩展 .

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

    $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
            )
    
    )
    
    推荐文章