【问题标题】:How do I access protected array key having a dollar sign inside a object (response from RTM-php)?如何访问对象内具有美元符号的受保护数组键(来自 RTM-php 的响应)?
【发布时间】:2017-03-19 23:10:23
【问题描述】:

当为 RTM (https://github.com/bartosz-maciaszek/php-rtm) 使用 php 库时,我收到了一个特定任务列表的响应,如下所示:

[notes] => Rtm\DataContainer Object

(
    [attributes:Rtm\DataContainer:private] => Array
        (
            [note] => Rtm\DataContainer Object
               (
                   [attributes:Rtm\DataContainer:private] => Array
                       (
                           [id] => 56254802
                           [created] => 2016-11-06T10:46:43Z
                           [modified] => 2016-11-06T10:49:26Z
                           [title] => null
                           [$t] => https://stackoverflow.com/questions/910912/extract-urls-from-text-in-php1
                       )

               )

        )

)

我可以得到id, created, modified 的值,但是$t 不起作用。

$note_obj = $obj->getNotes()->getNote();
$note_id = $note_obj->getId();
echo "$note_id\n";  //works fine

$note_content = $note_obj->get{'$t'}(); //doesn't work
print_r($note_content); 

显然$note_obj->get{'$t'}; 在这里失败.....那么我该如何访问这些数据?

【问题讨论】:

  • 试试$note_obj->{'get$t'}();
  • @Dekel 不。那也没有用。 PHP Fatal error: Uncaught BadMethodCallException: Method get$t not implemented in https://github.com/bartosz-maciaszek/php-rtm/blob/master/src/Rtm/DataContainer.php.....看着DataContainer.php,我找到了一种将对象转换为数组的方法。可能这就是要走的路。我会在这里尝试和评论。
  • 试试var_dump(get_class_methods($note_obj)); 看看你是否有任何特定的方法可以用来获取所有值。
  • 哇!...它成功了....非常感谢您指出正确的方向。
  • 哪种解决方案? :)

标签: php arrays object protected


【解决方案1】:

我发现类的所有方法都由DataContainer.php 处理,它有一个类似toArray 的方法将对象转换为数组。

这些方法也可以通过(正如@Dekel 在评论中指出的那样)公开:

var_dump(get_class_methods($note_obj));给了

array(10) {
[0]=>
string(11) "__construct"
[1]=>
string(11) "getIterator"
[2]=>
string(5) "count"
[3]=>
string(6) "__call"
[4]=>
string(3) "get"
[5]=>
string(3) "set"
[6]=>
string(3) "has"
[7]=>
string(6) "remove"
[8]=>
string(7) "toArray"
[9]=>
string(6) "toJson"
}

因此代码是:

$note_obj = $obj->getNotes()->getNote();
$rtm_item_note_content = $note_obj->toArray();
$rtm_item_note_content = $rtm_item_note_content['$t'];
echo "note content: $rtm_item_note_content\n";

完成!

【讨论】:

    猜你喜欢
    • 2014-07-11
    • 2011-01-06
    • 2014-10-15
    • 1970-01-01
    • 2020-11-07
    • 2016-03-26
    • 1970-01-01
    • 2013-04-09
    • 2013-01-22
    相关资源
    最近更新 更多