【问题标题】:How to detect if a class property is private or protected如何检测类属性是私有的还是受保护的
【发布时间】:2012-01-16 20:01:48
【问题描述】:

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

【问题讨论】:

标签: php oop


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    【解决方案3】:

    用途:

    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
    )
    

    还是我误解了你的帖子?哈哈

    【讨论】:

    • 我认为 OP 希望能够以编程方式检测属性是私有的还是公共的。如果他只是想知道,他可以打开文件。
    • 哦,我的错。一旦他接受指向反思的答案,我将删除我的帖子以避免混淆其他人:D
    • 不必。仅仅因为它不是最有用的答案,并不意味着它完全没用。其他人可能会在谷歌上搜索它,实际上只需要对问题进行 print_r 可视化。
    • 我明白了.. 好的,谢谢@mario,我会保留这篇文章.. 给您带来的任何麻烦,我们深表歉意
    猜你喜欢
    • 2013-08-14
    • 2011-10-11
    • 2023-03-04
    • 2011-05-29
    • 2016-08-13
    • 2018-08-19
    • 1970-01-01
    • 2011-12-12
    • 2013-10-10
    相关资源
    最近更新 更多