Yesterday evening Stephan wrote about
the object type hint. Coincidentally, while being in my
favourite bar, I was talking with
Timm Friebe, a colleague of mine, about the
scalar type hint:
function bar(scalar $baz) { ... }
This type hint would allow passing integers, floats, strings and boolean values, but no objects, arrays, resources and null values (null would be allowed if you make it
function bar(scalar $baz = null) similarly to how type hints work until now).
Having this type hint would have some advantages: you may never pass objects or arrays into this function which will be converted to strings, this will throw an E_CATCHABLE. It also still adheres to the PHP way I believe, because it does not specify the concrete scalar type and lets you the choice about it. Splitting this much more into strings, integers and so on is oversized and would not fit into PHP. (That it would be possible has already been
demonstrated by Derick.)
However I think it is not that necessary, but it rounds off the whole type hint story in PHP and would allow doing some stuff with arrays (now I'm going really mad

):
Arrays with type hints
$foo = array<scalar>();
$bar = array<MyClass>();
This first would be an array consisting of scalar values, the second an array of MyClass instances.
$foo = array<scalar,MyClass>()
This would be a hashmap which takes only instances of MyClass as values. It would be helpful to the IDE as well, because iterating over the array with
foreach ($foo as $myClass) { ... } the IDE would know that $myClass is an instance of MyClass and can offer code completion.
Now we can use it as type hints on functions and methods as well:
function foo(array<scalar,MyClass> $bar) { ... }
Something similar to this has
already been suggested in php-internals, but
turned down by one of the core developers. The proposal of Sebastian is nice, but from my point of view it doesn't fit into PHP because PHP developers are not used to such a notation (too much Java as well

).
Yes, my proposal looks a bit like
Generics. It would be enough to have this for arrays, there is no need to have generics for objects in PHP, as mostly arrays are used for such stuff in PHP.
But stop dreaming. My guess is that this will never be implemented in PHP, at least not in the official distribution.


