Skip to content
Advertisement

Can a PHP function expect a type?

I’m trying to do something like this:

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:

$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.

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;
}

Example on sandbox

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement