PHP - Using Hints to Check Method Arguments


Consider the following code:



        class Truck {
          public $color;
        }//from  w w  w .  j  av a  2 s .c  o  m

        class Garage {
          public function paint(Truck $truck, $color) {
            $truck->color = $color;

$truck = new Truck;
$garage = new Garage;
$truck->color ="blue";
echo $truck->color; // Displays"green"


This code creates two classes: Truck, with a single $color property, and Garage, with a paint() method.

This method takes a Truck object and a color string, and changes the Truck's $color property to the string provided.

The code uses a hint to tell PHP that Garage::paint() should expect a Truck object as its first argument, and reject any other type of argument.

To do this, you simply place the class name before the argument name.

You can use type hinting with regular functions, not just methods, and you can check that an argument is an array using hinting:

function showAll(array $items) {

PHP supports type hinting only for objects and arrays.

Related Topic