我从外部获取了一些数据,但是得到了这个错误,因为变量是"空":
未定义的属性:第68行的/Applications/MAMP/htdocs/jobportal/functions.php中的stdClass :: $ summary
我试图建立一个功能来帮助我:
$summary = convert_empty($user->summary);
function convert_empty($data) {
if(isset($data)) {
return $data;
} else {
return ".";
}
}
但错误仍然存在。我尝试过isset
,empty
和defined
。我想我在这里错过了另一个观点 - 因为它都不起作用。
答案 0 :(得分:2)
问题不在您的功能中,而是您如何称呼它。错误是您尝试访问->summary
但不存在。你可以使用这样的东西:
$summary = convert_empty($user, 'summary');
function convert_empty($data, $key) {
if (isset($data->$key))
return $data->$key;
return ".";
}
请注意,您还应该测试$data
是否也是对象。
if (is_object($data) && isset($data->$key)) { ... }
或者,没有使用条件三元运算符的函数:
$summary = isset($user->summary) ? $user->summary : '.';
编辑以便更深入地使用:
convert_empty($user, 'positions', 'values', $i, 'title');
function convert_empty($obj) {
$error = '.';
$args = func_get_args();
array_shift($args); // remove $obj
$ref = $obj ;
foreach ($args as $arg) {
if (is_array($ref)) {
if (!isset($ref[$arg])) return $error ;
$ref = $ref[$arg] ;
}
elseif (is_object($ref)) {
if (!isset($ref->$arg)) return $error ;
$ref = $ref->$arg ;
}
}
return $ref ;
}
答案 1 :(得分:1)
这意味着对象$ user没有定义汇总成员变量。
$summary = isset($user->summary) ? convert_empty($user->summary) : NULL;
或者
$summary = isset($user->summary) ? convert_empty(isset($user->summary) ? $user->summary : NULL);
现在你不会看到警告,并且$ summary将被设置为NULL,假设你在$ user->摘要未定义的情况下期望$ summary为NULL。 / p>
第二个允许你的convert_empty弄明白。