如何检测类属性是私有的还是受保护的


How to detect if a class property is private or protected

我如何检测如果一个类属性是私有的或受保护的没有使用外部库(纯PHP)?如何检查是否可以从类外部设置属性或不能设置属性?

使用反射

<?php
    class Test {
        private $foo;
        public $bar;
    }
    $reflector = new ReflectionClass(get_class(new Test()));
    $prop = $reflector->getProperty('foo');
    var_dump($prop->isPrivate());
    $prop = $reflector->getProperty('bar');
    var_dump($prop->isPrivate());
?>

使用Reflection

  • http://www.php.net/manual/en/reflectionclass.getproperties.php
  • http://www.php.net/manual/en/reflectionproperty.isprivate.php
  • http://www.php.net/manual/en/reflectionproperty.isprotected.php

使用说明:

print_r($object_or_class_name);

它应该为您绘制出您可以或不可以访问的属性。

例如:

class tempclass {
    private $priv1 = 1;
    protected $prot1 = 2;
    public $pub1 = 3;
}
$tmp = new tempclass();
print_r($tmp);
exit;

只是为了说明我有一个私有财产,一个受保护财产和一个公共财产。然后我们看到print_r($tmp);的输出:

tempclass Object
(
    [priv1:tempclass:private] => 1
    [prot1:protected] => 2
    [pub1] => 3
)
还是我误解了你的帖子?哈哈