简体   繁体   English

PHP stdClass对象,使用Constants访问

[英]PHP stdClass object, access with Constants

The response is received in JSON, $requestBody holds the json response. 响应以JSON 格式接收, $ requestBody保存json响应。 The type of that class is stdclass. 该类的类型是stdclass。

Now, if I access it using 现在,如果我使用它来访问它

   $myCar=$requestBody->Car;

The value in $myCar is "Alpha". $ myCar中的值是“Alpha”。 So, far so good. 到现在为止还挺好。

I have defined a constants like, defined in "MyConstants.php" 我定义了一个常量,如“MyConstants.php”中定义的

   define("ITEM1","Car");

So, I am trying to access values from $requestBody using Constant. 所以,我试图使用Constant从$ requestBody访问值。 But I get nil. 但我没有。 the code is listed below in "index.php" 代码在下面的“index.php”中列出

<?php 

include 'MyConstants.php';

//Works 
$key=constant("ITEM1");
$carStr=$requestBody->key;

//Does not work 
$carStr2=$requestBody->constant("ITEM1");
?>

Try the following: 请尝试以下方法:

$requestBody->{ITEM1}

You might also consider to decode the json to an array: 您可能还会考虑将json解码为数组:

$requestBody = json_decode($json, true);
$requestBody[ITEM1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM