Accessing StdClass value with colon :protected

时光总嘲笑我的痴心妄想 提交于 2019-12-02 20:37:02

问题


How do I access the value of stdClass with colon ":protected"?

For example, I had this $obj with these result :

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"

For example, I tried to access "kind" value which is "plus#person" using these code :

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

Well, they don't seems to work...Any idea how to access that protected data?

Thanks


回答1:


It's not a stdClass object, it's an object of the class Google_Service_Plus_PeopleFeed. You cannot access protected properties of a class [easily]. If the class doesn't want you to access the data, then you shouldn't. But typically the class offers some method you can call to get the data, like $obj->getData() or some such. Look at the class definition or its documentation to see how you're supposed to use the class.




回答2:


You can't access to a protected property from outside this object. Look at http://www.php.net/manual/en/language.oop5.visibility.php




回答3:


Well, I can finally access it with :

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

Anybody can explain why? Just curious why it needs to be protected >.<




回答4:


Please note that there is probably a reason that these properties are protected, so you should think twice before trying to access them.

If you need to access protected variables, you could use Reflection, but there might be an easier solution. By binding a closure to the object, you should be able to access the protected variables from the closure:

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


来源:https://stackoverflow.com/questions/20968912/accessing-stdclass-value-with-colon-protected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!