Skip to content
Advertisement

Can a PHP function expect a type?

I’m trying to do something like this:

JavaScript

So that I can call it in an echo or a foreach like this:

JavaScript

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

Example on sandbox

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