< Day Day Up > |
13.8 Classes and ObjectsPHP 5 provides comprehensive and robust support for object-oriented programming. If you've never heard of object-oriented programming, then you don't need to use any of these fancy features. But if you're coming to PHP from a language such as Java, you can structure your code in familiar ways. You can create interfaces; abstract classes; public, private, and protected properties and methods; constructors and destructors; overloaded property accessors and method dispatchers; and plenty of other OO goodies. Chapter 2 of Upgrading to PHP 5 by Adam Trachtenberg (O'Reilly), lays out the many object-related changes in PHP 5. The PHP Manual covers classes and objects at http://www.php.net/manual/language.oop.php. 13.8.1 Object BasicsAn object, in the programming world, is a structure that combines data about a thing (such as the ingredients in an entree) with actions on that thing (such as preparing the entree). Using objects in a program provides an organizational structure for grouping related variables and functions together. Some words to know when working with objects are defined in the following list:
13.8.2 Creating a New ObjectPEAR DB uses a static method to create a new object instance for you to use: $db = DB::connect($dsn); This calls the connect( ) method defined in the DB class. The connect( ) method is a static method: nothing in connect( ) depends on a specific instance of the DB class. The classname::method( ) syntax is how you call a static method. When you see two colons in a function name like that in a PHP program, think "static method call." The other way to create a new object is with the new operator: $dinner = new Entree( ); This makes the variable $dinner an instance of the class Entree. To pass arguments to a class's constructor, put them in the parentheses: $dinner = new Entree('Chinese','spicy'); 13.8.3 Accessing Properties and MethodsThe -> ("arrow") operator, composed of a hyphen and a greater-than sign, is your road to the properties (variables) and methods (functions) inside an object. To access a property, put the arrow after the object's name and put the property after the arrow: print $dinner->price; $todays_fat = $todays_fat + $dinner->fat; print 'To eat: '. strtoupper($dinner->name); To call a method, put the method name after the arrow, followed by parentheses: $dinner->prepare( ); $ingredients = $dinner->get_ingredients( ); You can pass arguments to a method just like a regular function: $has_pineapple = $dinner->contains('Pineapple'); $dinner->add_ingredient('Ginger Root'); $dinner->serve('Alice','Bob','Charlie'); Note that the arrow operator used to access properties and methods is different than the operator-separating array keys and values in array( ) or foreach( ). The array arrow has an equals sign: =>. The object arrow has a hyphen: ->. |
< Day Day Up > |