使用冒号访问StdClass值:protected

时间:2014-01-07 10:12:18

标签: php stdclass

如何使用冒号“:protected”?

访问stdClass的值

例如,我有这个$ obj这些结果:

object(Google_Service_Plus_PeopleFeed)#14 (11) {
  ["title"]=>
  string(30) "Google+ List of Visible People"
  ["totalItems"]=>
  int(4)
  ["collection_key:protected"]=>
  string(5) "items"
  ["data:protected"]=>
  array(1) {
    ["items"]=>
    array(2) {
      [0]=>
      array(7) {
        ["kind"]=>
        string(11) "plus#person"
        ["etag"]=>
        string(57) ""42gOj_aEQqJGtTB3WnOUT5yUTkI/1eNkvlfeTwXXldr9rYAvMcwM6bk""
        ["objectType"]=>
        string(6) "person"

例如,我尝试使用以下代码访问“kind”值“plus#person”:

$kind = $obj->{'data:protected'}->items[0]->kind; //-> returns NULL
//OR
$kind = $obj->{data:protected}->items[0]->kind; //->returns error on ":"

嗯,它们似乎不起作用......知道如何访问受保护的数据吗?

由于

4 个答案:

答案 0 :(得分:4)

它不是stdClass对象,它是类Google_Service_Plus_PeopleFeed的对象。您无法轻松访问类的受保护属性。如果班级不希望您访问数据,那么您不应该。但通常这个类提供了一些方法,你可以调用它来获取数据,比如$obj->getData()或其他类似的方法。查看类定义或其文档,了解您应该如何使用该类。

答案 1 :(得分:1)

您无法从此对象外部访问受保护的属性。看http://www.php.net/manual/en/language.oop5.visibility.php

答案 2 :(得分:0)

好吧,我终于可以通过以下方式访问它了:

$kind = $obj['data']['items'][0]['kinds'];

任何人都可以解释原因吗?只是好奇为什么需要保护>。<

答案 3 :(得分:0)

请注意,可能有这些属性受到保护的原因,因此在尝试访问它们之前应该三思而后行。

如果您需要访问受保护的变量,可以使用Reflection,但可能有一个更简单的解决方案。通过将闭包绑定到对象,您应该能够从闭包中访问受保护的变量:

class X {
   protected $a = 10;
   public $b = 20; 
}


$closure = function() {
          return get_object_vars($this);
};

$result = Closure::bind($closure, new X(), 'X');
var_dump($result());