I’m trying to do something like this:
JavaScript
x
function get_value($value)
{
if (is_null($value)) {
if ($value expects array) {
return ['hello', 'world'];
}
else {
return 'hello world';
}
}
return $value;
}
So that I can call it in an echo or a foreach like this:
JavaScript
$value = null;
foreach(get_value($value) as $value) {
echo $value;
}
echo get_value($value);
So the foreach would expect an array, but the echo would expect a string.
Is this possible?
Advertisement
Answer
It is not possible to use functions like that.
However, if you go a bit further and start using objects then you can actually achieve that by creating a class that implements the IteratorAggregate interface together with defining the __toString()
magic method.
JavaScript
class GetValue implements IteratorAggregate
{
private $value;
public function __construct($value = null)
{
$this->value = $value === null ? ['hello', 'world'] : (array) $value;
}
public function getIterator() {
return new ArrayIterator($this->value);
}
public function __toString()
{
return implode(' ', $this->value);
}
}
$valueIterator = new GetValue();
echo $valueIterator;
foreach ($valueIterator as $key => $value) {
echo "n" . $key . ' => ' . $value;
}