如何在名称中使用$字符访问/转义PHP对象成员?

时间:2021-09-20 04:51:44

I'm decoding some JSON (from the Youtube data API) with json_decode and it gives me an object that looks like this when var_dump()ed:

我正在用json_decode解码一些JSON(来自Youtube数据API),它给我一个在var_dump()ed时看起来像这样的对象:

object(stdClass)[29]
  public 'type' => string 'text' (length=4)
  public '$t' => string 'Miley and Mandy! KCA VIDEO WINNERS' (length=34)

How can I access the $t member?

我如何访问$ t成员?

3 个解决方案

#1


Try

$member = '$t';
$obj->$member

#2


You may use the second argument of json_decode

您可以使用json_decode的第二个参数

$data = json_decode($text, true);
echo $data['$t'];

#3


$t will only interpreted as a variable reference when used outside of quotes, or within double quotes ("$t"). Strings enclosed in single quotes ('$t') are not parsed for variable references.

$ t仅在引号之外使用时或双引号(“$ t”)内被解释为变量引用。用单引号('$ t')括起来的字符串不会被解析为变量引用。

echo $data['$t'];

Will do exactly what you want.

会做你想要的。

#1


Try

$member = '$t';
$obj->$member

#2


You may use the second argument of json_decode

您可以使用json_decode的第二个参数

$data = json_decode($text, true);
echo $data['$t'];

#3


$t will only interpreted as a variable reference when used outside of quotes, or within double quotes ("$t"). Strings enclosed in single quotes ('$t') are not parsed for variable references.

$ t仅在引号之外使用时或双引号(“$ t”)内被解释为变量引用。用单引号('$ t')括起来的字符串不会被解析为变量引用。

echo $data['$t'];

Will do exactly what you want.

会做你想要的。