9.1 Creating a Class


You know what classes are, and you want to create one in PHP.

Technique

Use the class declaration to create a class:

 <?php class Car {     //... The data of your class goes here. } ?> 

Comments

The declaration of a class in PHP is as simple as it gets. What you see in the preceding code is exactly what you do. After you declare the class, you can put all member methods and attributes inside the curly brackets and you have a class. Consider the following example:

 class Name {     var $property1;     var $property2;     function print_name($first_name, $last_name) {         print "Your first name is: $first_name, ";         print "and your last name is: $last_name";     } } 

You now have a class that contains both methods ( print_name() , in this case) and attributes ( $property1 and $property2 ). Note the var statement when declaring variables; this makes the variables attributes of the class, and therefore accessible by objects of the class. This concept leads us to the next subject of this recipe.

Instances, also referred to as objects, are specific implementations of a class. A good analogy is saying that an instance (object) is related to a class like a house is related to its blueprint.

Taking the Name class defined earlier in this recipe, you need to create an instance of the class in order to work with the class for individual cases. To do this, you need to use PHP's new statement, which automatically creates an object from the specified class. That means memory is set aside for the object, necessary initialization is performed, and the class attributes and methods are now accessible through the object by using the arrow notation:

 <?php // Create new object $obj = &new Name; // Set $firstname in class Name equal to the string Oliver $obj->firstname = 'Oliver'; // Set $lastname in class Name equal to the string Butin $obj->lastname  = 'Butin'; // Call the print name method in Class name $obj->print_name($obj->firstname, $obj->lastname); ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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