May.01Type hinting in PHP
Type hinting is a php5 feature that can be really helpful in OO-driven development. It is a very common feature seen in any strongly-typed language.
It forces to pass the parameters of functions and methods to be of certain types. But it still lacks something important. Type hinting is only possible for classes and array.
There is no support for scaler data types(like int, string,…). I hope this will be supported in any recent release.
Here is how we can use type hinting.
{
if(is_array())
echo ‘$config is an array’;
else die(‘$config is not an array!!!’);
}
foo
(array(‘dbhost’=>localhost,‘dbuser’=>‘me’));/* This will throw a fatal error.
$var = 1;
foo($var);
*/
Here is another example using class.
{
public function getName()
{
return __CLASS__;
}
}
$instance = new MyClass;
sayName($instance);
It is possible to pass a child object when a parent object was hinted in the declaration.
class MyClass
{
public function getName()
{
return __CLASS__;
}
} class ChildClass extends MyClass
{
} function sayName(MyClass $obj)
{
echo $obj->getName();
} $instance = new ChildClass;
sayName
($instance);Type hinting can be helpful to eliminate bug very quickly. It will save a lot of coding for error checking. I hope php will support type hinting for function return types as well.

Leave a Reply