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

时间:2011-12-09 14:34:54

标签: php oop

如何检测类属性是私有还是受保护没有使用外部库(仅限纯PHP)?如何检查我是否可以从课外设置属性,或者我不能?

3 个答案:

答案 0 :(得分:8)

使用Reflection.

<?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());
?>

答案 1 :(得分:5)

答案 2 :(得分:0)

使用:

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
)

或者我误解了你的帖子?哈哈

相关问题