首页 > 解决方案 > 数组到对象抛出未捕获的错误:调用未定义的方法 stdClass

问题描述

我正在尝试从代码中重建一个对象。首先我将对对象的调用分解为数组,然后将数组转换为对象,然后测试调用是否有效。

创建的对象看起来不错,但测试调用失败。

$claim = new_client();
print_r($claim);
$pat = $claim->patientFirstName();
echo $pat;

function new_client()
{
$text = '
$claim->patientFirstName() 
UNWANTED STUFF. 
$claim->patientMiddleName()
UNWANTED STUFF.....
$claim->patientLastName() ';


$client = array();
$i = 1 ;
$array =  (explode("claim->",$text));

foreach ($array as &$variable) {
$variable = substr($variable, 0, strpos($variable, "()"));

$client[$variable] = $i;
$i++;
}
unset ($variable);
$object = new stdClass();
foreach ($client as $key => $value)
{
$object->$key = $value;
}
return $object;
}

这是结果。

stdClass Object ( [] => 1 [patientFirstName] => 2 [patientMiddleName] => 3 
[patientLastName] => 4 ) 
Fatal error: Uncaught Error: Call to undefined method 
stdClass::patientFirstName()...

所以关于为什么 $pat = $claim->patientFirstName(); 的任何想法 失败了吗?

标签: phparraysobject

解决方案


您正在访问元素是错误的方式。

$claim->patientFirstName
$claim->patientMiddleName

推荐阅读