Is it possible for a function or method in PHP to determine whether the caller expects an array return value or not (ala Perl’s wantarray operator)? Specifically, I’d like to create a __get() magic method that automatically returns an array if the caller expects one, and a sensible scalar value if not. So something like this:
public function __get($name)
{
if (wantarray())
{
// data is stored internally as an array of arrays
// return appropriate array as-is
return $this->data[$name];
}
else
{
// caller doesn't expect an array, return imploded string instead
return implode(', ', $this->data[$name]);
}
}
Basically, does PHP have an equivalent to Perl’s wantarray operator or otherwise allow for the determination of this sort of calling context?
No, You could not do this with PHP.
You just need to return
$this->data[$name]and let the caller decide whether it is necessary to doimplodeor not.