PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

More on scalar type hints in PHP trunk

Note: This article was originally published at Planet PHP on 22 November 2010.
Planet PHP

Some time ago I wrote an article about the implementation of type hints for non-object types for PHP. Meanwhile many things happened and that implementation was replaced by a different one. Readers of my previous post might know that I have doubts about type hints in PHP. People who met me in person and asked me about it know for sure

So what's the status now? - Well type hints, for non-object types, exist and they don't. There is a valid syntax which looks like this:

function foo(int $i) { AAA echo $i; }

What's the consequence of this code? - Well the type hint is simply ignored. This means that

Afoo("Hello world");

Will run without any error and print Hello world. So there is an syntax looking like another part of the language which throws errors but behaves completely different.

function foo(bar $b) { } foo("bar");'Catchable fatal error: Argument 1 passed to foo() must be an instance of bar, string given [...]

The int hint is just one of them, there are a few more:

  • bool, boolean
  • string, binary
  • scalar
  • numeric
  • int, integer, long
  • real, double, float
  • resource
  • object
So why is there a syntax added which is ignored? Well there are two things one can do: The hint can be read via the tokenizer to do some magic or one might create a PHP extension which hooks into the engine to do stricter checks on this, like for a testing system. Does it make sense? - Well, I let it to you to decide whether it make sense to have two syntaxes which look the same but do very different things (being ignored vs. throwing a terminating error) and whether it makes sense to push a system where the core language behaves differently depending on the system (is an extension using this hook loaded? which of them? - one which casts or one which throws an error?) ... I seriously hoped PHP was out of the era of introducing new inconsistencies ...