在对象中获取私有值

时间:2015-04-20 09:50:37

标签: php

我生成了这些数据,但是如何获取数据的值,例如

用户ID - > [id] => 1429517

消息 - > [data:ProtocolNode:private] =>得到我的消息

Array
(
[0] => ProtocolNode Object
    (
        [tag:ProtocolNode:private] => message
        [attributeHash:ProtocolNode:private] => Array
            (
                [id] => 1429517
                [offline] => 0
                [type] => text
                [t] => 14722889
            )

        [children:ProtocolNode:private] => Array
            (
                [0] => ProtocolNode Object
                    (
                        [tag:ProtocolNode:private] => body
                        [attributeHash:ProtocolNode:private] => Array
                            (
                            )

                        [children:ProtocolNode:private] => 
                        [data:ProtocolNode:private] => get my message
                    )

            )

        [data:ProtocolNode:private] => 
    )

)

我尝试过使用它:

    foreach($msgs as $msg) {
    echo 'test: ' . $msg->tag ; 
    }

但是我收到了错误:

致命错误:无法访问私有属性ProtocolNode :: $ tag

1 个答案:

答案 0 :(得分:1)

$reflection = new ReflectionClass($msg);
$prop = $reflection->getProperty("tag");
$prop->setAccessible(true);
$tag = $prop->getValue();

但是这有点破解方式,如果你有自己的ProtocolNode,那么最好添加getter" getTag",如果ProtocolNode是某个供应商的lib类,那么你可以将ProtocolNode扩展到MyProtocolNode,添加getter