14.2 Class Type Hints


The class type hint feature is available in PHP5.

PHP is a loosely typed language, and this allows different types of data to be passed as parameters into functions. When user-defined functions or class member functions are designed to work with object parameters, it is often useful to check the type of object before it is used. PHP5 allows you to specify the type of object parameter with a class type hint. Consider the following example that defines a function to return information about Shape objects:

// User-defined function that returns information about a Shape // object function shapeInfo(Shape $shape) {     return "I have a {$s->color( )} shape with {$s->sides( )} sides"; }

The definition of the function shapeInfo( ) includes the class type hint Shape before the parameter $shape. This instructs PHP to check the class of $shape when the script is run. If the function is called with an object that is not a Shape, or even a value that was not an object, PHP causes the script to terminate with a fatal error.

Using class type hints is the equivalent of checking the parameter with the instanceof keyword. Using this approach, the shapeInfo( ) function could be rewritten as:

// User-defined function that returns information about a Shape // object function shapeInfo($shape) {     if (not $shape instanceof Shape)         die ("Parameter not a Shape object");     return "I have a {$s->color( )} shape with {$s->sides( )} sides"; }



Web Database Application with PHP and MySQL
Web Database Applications with PHP & MySQL, 2nd Edition
ISBN: 0596005431
EAN: 2147483647
Year: 2003
Pages: 176

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net