PHP type hinting for scalar data types, a step closer

Citește postarea în română

Share on:

In PHP 5 a new concept was introduced, type hinting. This feature allows validation of a parameter for a certain type.

This validation type is very popular in object orientated languages and I believe it represents a plus for the PHP object model and even more for his dynamic nature it self.

In PHP 5.1 validation for the array data type was added.

Let’s take a small example:

 1class a { }
 2
 3class b { }
 4
 5function testa (a $a) {
 6    echo "Bla bla\n";
 7}
 8
 9testa(new a());
10
11testa(new b());

The result is:

1Bla bla
2
3Fatal error: Argument 1 passed to testa() must be an instance of a, called in ...

Cool, ha?

The type in which we can validate can be a class, an abstract class or even an interface which is inherited  by other classes, like:

 1interface inherited { }
 2
 3class a implements inherited { }
 4
 5class b implements inherited { }
 6
 7function testa (inherited $a) {
 8    echo "Bla bla\n";
 9}
10
11testa(new a());
12
13testa(new b());

And the above example will not raise any errors.

Unfortunately there is no way to validate primary (or scalar) data types. When PHP 5.3 was being released there have been some discussions on the subject, but it seems that it was too late, and the patch did not make it to the final version.

Yesterday, while I was doing my morning reading at a cup of coffee, what do I see on Ilia Alshanetsky blog: Scalar Type Hints are Here! Well, is a little exaggerated, there are not exactly here but there really close. Basically there are in the SVN trunk and will be available in the next stable version!

Of course that even in the current version of type hinting is not exactly mandatory to use it in PHP, is more of an issue of fine tune.

Basically we could already validate to a certain primary data type, but still:

1function testint($var) {
2     if(!is_int($var)) {
3         trigger_error("Type must be Integer", E_USER_ERROR);
4     }
5     .......
6}

is not exactly as elegant as:

1function testint(int $var) {
2     ......
3}