【问题标题】:PHP access object values dynamically by variable namePHP通过变量名动态访问对象值
【发布时间】:2016-01-14 09:28:00
【问题描述】:

我有这个小sn-p:

$action = $_GET['action'];
// some other code

// works
$properties = $client->__soapCall($action, array(
    array(
        'Page' => $x
    )
));

// try to get access to values by var $action
$obj = $properties->$action->item;

这给了我一个错误。我的意图是通过获取不同的操作,仅将脚本用于多次操作。

...但我不知道如何解决这个问题,也没有找到任何有用的帖子或文章。

var_dump($properties):

object(stdClass)#84 (4) {
    ["PropertyGroups"]=>
        object(stdClass)#85 (1) {
            ["item"]=>
                array(73) {
                    [0]=>
                        object(stdClass)#86 (7) {
                            ["PropertyGroupID"]=>int(1)
                        }
                }
          }
  }

【问题讨论】:

  • This gives me an error. 我们应该猜对了吗?
  • 不,你不应该。对不起。如果action = GetPropertyGroupsUndefined property: stdClass::$GetPropertyGroups
  • var_dump($properties)
  • 你使用的是什么 PHP 版本?
  • 我目前使用的是 PHP 5.5.30,但可以升级到 7.0.1

标签: php variables object


【解决方案1】:

脚本和这一行

$obj = $properties->$action->item;

绝对没问题。但是,正如您在 cmets 中指出的那样,

如果 action = GetPropertyGroups,未定义属性: stdClass::$GetPropertyGroups

您在$properties 中有PropertyGroups 属性,不是GetPropertyGroups

您应该检查您要查找的属性是否存在:

property_exists($properties, $action)

【讨论】:

  • 你是绝对正确的。这是我的错误,我没有看到。谢谢!
猜你喜欢
  • 2014-04-25
  • 2013-06-04
  • 2014-10-11
  • 1970-01-01
  • 2019-01-26
  • 2017-07-05
  • 1970-01-01
  • 2022-04-26
  • 2021-05-21
相关资源
最近更新 更多