【问题标题】:How do you validate if a property is accessible in php?你如何验证一个属性是否可以在 php 中访问?
【发布时间】:2016-07-07 19:32:57
【问题描述】:

对于包含私有属性的类,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

?> 

【问题讨论】:

    标签: php class object methods properties


    【解决方案1】:

    您可以使用Reflection class 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
            )
    
    )
    

    【讨论】:

    • 谢谢。奇怪的是,检查函数可以用简单的php函数完成,但属性需要使用反射类!
    • @Joe
       function isPublic($property, $object) { $r_object = new ReflectionObject($object); $properties = $r_object->getProperties(ReflectionProperty::IS_PUBLIC); if (is_array($properties) && count($properties) >0) { foreach ($properties as $ppt) { if ($ppt->name == $property) { return true; } } } 返回错误; } 
    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多