【问题标题】:php: variable in object not workingphp:对象中的变量不起作用
【发布时间】:2011-09-16 15:22:29
【问题描述】:

为对象使用变量但我无法访问该对象,您可以在下面查看我的代码

 $score = $score[1];
    $score = ''.$score.'';
    $score_data = $data_json2->$score;

    if (!empty($score_data)) {return ja;}
    else {return nein;}

尝试了几件事,但不知道我的错在哪里,请对我的代码提出建议,以便它可以工作

【问题讨论】:

  • 请澄清您在这里尝试做什么以及失败的地方
  • 所以你正在尝试获取 $score 值的对象。不会是 $data_json2->{$score}; ?
  • 您知道$score 与$data_json2->score 完全不同吗?请注意,它是$object->variable,而不是$object->$variable(没有第二个$)。
  • 你为什么返回ja和nein?这些是常数吗?
  • @Ryan 这两个是等价的。

标签: php variables object


【解决方案1】:

您的代码有很多问题。

$score      = $score[1];
//$score    = ''.$score.''; <- useless, you add nothing to the start and end
$score_data = $data_json2->{$score}; // I suppose this is what you're trying to do

if (!empty($score_data)) {return 'ja';}
else {return 'nein';} // unless ja and nein are constants, you need to add quotes

问题可能在于$data_json2-&gt;$score 而不是$data_json2-&gt;{$score}。

我会这样重写你的代码:

$score_data = $data_json2->{$score[1]};

return empty($score_data) ? false : true;

【讨论】:

  • $var-&gt;$prop 和 $var-&gt;{$prop} 在功能上是相同的。后一种语法的存在是为了在某些情况下消除歧义,例如$var-&gt;{$prop-&gt;something}。我只能假设 ''.$score.'' 用于将数字分数转换为字符串。
  • 你可以有效地做 $foo->$bar,它的注册和 $foo->{$bar} 一样在这里阅读更多:php.net/manual/en/language.variables.variable.php
  • $score = $score[1]; $score_data = $data_json2->{$score}; if (!empty($score_data)) {return "ja";} else {return "nein";} 它总是说 "nein"
【解决方案2】:

不知道$score 或$data_json2 包含什么,我只能建议对这两个变量使用var_dump() 并验证它们是否具有您认为的结构。

【讨论】:

  • score 是一个字符串 data_json2 是一个包含诸如 apple 等元素的对象,所以当 score = apple 它应该重新调整 ja 但它没有?
猜你喜欢
  • 2017-08-21
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多