PHP 5: Class hinting

Class hinting is where the class of object to be passed into a method is specified in the function call.


abstract class User
 protected $logState;

 public function User()
  $this->logState = new LogState()

 public function setLogstate(LogState $logState)
  $this->logState = $logState;

This code will throw a runtime error if the variable passed into the setLogstate method is anything but a LogState object.

The benefits of this are twofold:

  • Errors in code are trapped at an earlier point in runtime. If the type was not checked then $this->logState may contain, for example, a string or other variable type and the mistake not caught until much further through processing making it more difficult to locate the source of the error.
  • The code is self-documenting as it is obvious to anyone reading the setLogstate method what class of object $logState will contain

The hint may not just be a class, it can also contain the name of an interface. Hence a method such as:

function saveSomething(Saveable $objectToSave)
 //Do things with $objectToSave

will allow through any object which implements the Saveable interface.

Leave a Reply

Your email address will not be published. Required fields are marked *