PHP - 我可以使用字符串作为对象吗?

时间:2017-07-16 21:07:32

标签: php json

假设我有以下JSON对象

/

现在考虑这个功能

$object = 
{
  "recipe": {
    "apples": 5
    "flour": "2 lbs"
    "milk": "2 cartons"
  }
}

如果我将private function get_quantity($ingredient) { $json = json_decode($object); return $json->recipe->{$ingredient}; } 传递给该函数并希望将milk作为输出。这可能在PHP吗?

3 个答案:

答案 0 :(得分:3)

是的,有可能。

供参考,见:

注意 $object在您的函数中未定义,您也应将其传入:

private function get_quantity($object, $ingredient)
{
    $json = json_decode($object);

    return $json->recipe->{$ingredient};
}

答案 1 :(得分:1)

是的,你可以做到。您的代码唯一的问题是语法。试试这个:

$object = '
{
  "recipe": {
    "apples": 5,
    "flour": "2 lbs",
    "milk": "2 cartons"
  }
}';

注意我添加了逗号,并用引号括起了JSON。

该方法定义明确,假设它可以 $object

答案 2 :(得分:1)

<?php
    $object = 
    '{
      "recipe": {
        "apples": 5,
        "flour": "2 lbs",
        "milk": "2 cartons"
      }
    }';

    function get_quantity($object, $ingredient) {
      $json = json_decode($object);
      return $json->recipe->{$ingredient};
    }

    var_dump(get_quantity($object, 'milk'));
    ?>