PHP5: Type Hinting

Posted on February 11, 2011

PHP5 introduces limited type hinting, sort of a concession to strong typing. You can tell a function that a parameter should be an array or a certain class:

function test(OtherClass $otherclass) {
  echo $otherclass->var;
}

function test_array(array $input_array) {
  print_r($input_array);
}

As you can see, for arrays you prefix the parameter name with the array keyword. For objects, you use the name of the class or interface (or “self” or “parent”). Right now, only arrays and classes are supported as the specified type. If you want type hinting for the scalar types, you’ll have to use an object-based (experimental) extension called SPL Types.

If, when the function is called, the passed object is not the correct type, the program will die with a fatal error. However, it’s a new type of error — E_RECOVERABLE_ERROR — so you can handle the error and continue with the rest of your program if you wish.

$otherclass = new OtherClass; 

// Fatal Error: Argument 1 must be an object of class OtherClass
test('hello');

// Fatal Error: Argument 1 must not be null
test(null);

// Works
test($otherclass);

// Fatal Error: Argument 1 must be an array
test_array('a string');

// Works
test_array(array('a', 'b', 'c'));

If NULL is used as the default parameter value, it will be allowed as an argument for any later call.

function test(OtherClass $otherclass = null) { ... }
test(null); // works
test(new OtherClass); // still works

Leave a Reply

  1.  

    |