CHAPTER 3 – CLASS TYPE HINTS IN FUNCTION PARAMETERS

3.20 CLASS TYPE HINTS IN FUNCTION PARAMETERS Although PHP is not a strictly typed language in which you would need to declare what type your variables are, it does allow you (if you wish) to specify the class you are expecting in your function's or method's parameters. Here's the code of a typical PHP function, which accepts one function parameter and first checks if it belongs to the class it requires: function onlyWantMyClassObjects($obj) { if (!($obj instanceof MyClass)) { die("Only objects of type MyClass can be sent to this function"); } ... } Writing code that verifies the object's type in each relevant function can be a lot of work. To save you time, PHP enables you to specify the class of the parameter in front of the parameter itself.

Following is the same example using class type hints: function onlyWantMyClassObjects(MyClass $obj) { // ... } When the function is called, PHP automatically performs an instan- ceof check before the function's code starts executing. If it fails, it will abort with an error. Because the check is an instanceof check, it is legal to send any object that satisfies the is-a relationship with the class type. This feature is mainly useful during development, because it helps ensure that you aren't passing objects to functions which weren't designed to handle them.

3.21 SUMMARY This chapter covered the PHP 5 object model, including the concept of classes and objects, polymorphism, and other important object-oriented concepts and semantics. If you're new to PHP but have written code in object-oriented lan- guages, you will probably not understand how people managed to write object- oriented code until now. If you've written object-oriented code in PHP 4, you were probably just dying for these new features.

Post Comment
Login to post comments