Reputation: 59
I get some data externally but gets this error because the variable is "empty":
Undefined property: stdClass::$summary in /Applications/MAMP/htdocs/jobportal/functions.php on line 68
I have tried to build a function to help me:
$summary = convert_empty($user->summary);
function convert_empty($data) {
if(isset($data)) {
return $data;
} else {
return ".";
}
}
But the error is still there. I have tried isset
, empty
, and defined
. I think I miss another point here - since none of it is working.
Upvotes: 3
Views: 17332
Reputation: 19780
The issue is not in your function, but how you call it. The error is that you're trying to access ->summary
but doesn't exists. You could use something like this:
$summary = convert_empty($user, 'summary');
function convert_empty($data, $key) {
if (isset($data->$key))
return $data->$key;
return ".";
}
Note that you should also test if $data
is an object too.
if (is_object($data) && isset($data->$key)) { ... }
Or, without a function using conditional ternary operator :
$summary = isset($user->summary) ? $user->summary : '.';
EDIT for a deeper use :
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 ;
}
Upvotes: 2
Reputation: 1772
That means that the object $user doesn't have a summary member variable defined.
$summary = isset($user->summary) ? convert_empty($user->summary) : NULL;
Or
$summary = isset($user->summary) ? convert_empty(isset($user->summary) ? $user->summary : NULL);
Now you won't see the warning and $summary will be set to NULL, assuming that you're expecting $summary to be NULL in this situation in which $user->summary is undefined.
The second one allows your convert_empty to figure it out.
Upvotes: 2