Section 5.3. Object-Oriented Programming


5.3. Object-Oriented Programming

Object-Oriented programming follows the same goals that we discussed when introducing functions, principally to make reusing code easier. It uses classes to group functions and variables together as an object. It may help to think of objects as little black boxes that can do work without you knowing exactly how it's done.

They still use functions, but they get a new name when defined in classes. They're called methods. The class works as a blue print for creating objects of that type. Variables can still be defined in methods, but they gain the new ability to be defined as part of the class itself.

When a new object is created from a class, it is called an instance of that class. Any variables that are defined in the class get separate storage space in each instance. The separate storage for variables provides the instance of an object with the ability to remember information between method executions. Figure 5-3 demonstrates the relationship between a class and its components.

Figure 5-3. A class can contain methods and attributes (variables)


If you're new to the concepts of OO programming, don't worry about understanding everything right away. We'll work with a class in Chapter 7, so it's good enough just to know how to call the methods. In fact, anything that can be done with objects can be done with plain functions. It's just a matter of style and personal preference.

5.3.1. Creating a Class

Classes are typically stored in separate files for reuse. Although we show the class, it isn't required. Let's build an object called Cat that has three methods: meow, eat, and purr. The class construct defines a class. It takes the name of the class immediately after it. Class names follow the same naming rules as variables and functions. The code that makes up the class is placed between curly brackets. This example creates the Cat class without defining any methods or variables.

You can do a quick check to see whether the class has been defined, as Example 5-10 demonstrates.

Example 5-10. Creating an object from the Cat class

 <?php class Cat { } $fluffy = new Cat(); echo "Fluffy is a new ".gettype($fluffy)."!"; ?> 

Example 5-10 displays:

 Fluffy is a new object! 

5.3.2. Creating an Instance

In Example 5-10, you not only defined the class but also created an instance of it. You used the new keyword to tell PHP to return a new instance of the Cat class. Although the class doesn't do anything, you can tell that it's defined as an object. The class is a blueprint for building instances. The class specifies what is included in each new instance of that class. Each instance can do everything the class defines, but does it independently of any other instance you've created.

5.3.3. Methods and Constructors

Methods are the functions defined within the class. They work within the environment of the class, including its variables. For classes, there is a special method called a constructor that's called when a new instance of a class is created to do any work that initializes the class, such as setting up the values of variables in the class. The constructor is defined by creating a method that has the same name as the class, as shown in Example 5-11.

Example 5-11. Creating the Cat constructor

 <?php class Cat {   // Constructor   function Cat() {   } } ?> 

PHP 5 supports a new syntax for creating a constructor method using _ _construct, as shown in Example 5-12. If a class in PHP 5 doesn't have this method, the old style of using the class name as the method name is used.

Example 5-12. Using the PHP 5 style constructor

 <?php class Cat {   // Constructor   >__construct(){   } } ?> 

The constructor may also contain parameters like any other method. Additionally, classes can contain user-defined methods. For the Cat class, you can define meow, eat, and purr, as shown in Example 5-13.

Example 5-13. Defining three member functions for Cat

 <?php Class Cat {   // Constructor   function Cat() {   }   // The cat meows   function meow() {     echo "Meow...";   }   // The cat eats   function eat() {     echo "*eats*";   }   // The cat purrs   function purr() {     echo "*Purr...*";   } } ?> 

When you declare a new instance of a class, the user-defined constructor is always called, assuming that one exists. As you know, a class provides the blueprint for objects. You create an object from a class. If you see the phrase "instantiating a class," this means the same thing as creating an object; therefore, you can think of them as being synonymous. When you create an object, you are creating an instance of a class, which means you are instantiating a class.

The new operator instantiates a class by allocating memory for that new object, which means that it requires a single, postfix argument, which is a call to a constructor. The name of the constructor provides the name of the class to instantiate, and the constructor initializes the new object.

The new operator returns a reference to the object that was created. Most of the time, this reference is assigned to a variable of the appropriate type. However, if the reference is not assigned to a variable, the object is unreachable after the statement in which the new operator finishes executing. Example 5-14 shows how not to use new, and then how better to use it.

Example 5-14. Creating a new object without saving the reference, then creating an object to keep around

 <?php new Cat; //the Cat object cannot be accessed since its reference wasn't saved $myCat=new Cat; //this time we've kept the new Cat object available ?> 

When declaring new instances of a class, if the constructor does not contain any parameters, it's optional to use parenthesis (()) after the class name in the new statement.


5.3.4. Variable Scope Within Classes

Classes may contain variables that help define their structure and how they are used. Variables inside a class are declared with the var statement. The var statement declares a variable to have class scope. Class scope means they're visible with any methods of the class and can be referenced outside the class using a special construct. Example 5-15 adds the $age variable to the Cat class.

Example 5-15. Adding the $age variable to Cat

 <?php class Cat {   // How old the cat is   var $age; } ?> 

When referring to methods and variables from within the class, you must use the syntax:

 $this->variable or method name; 

The special variable $this always points to the currently executing object.

In Example 5-16, the this-> operator is used to modify the value of $age. The arrow is similar to the dot (.) notation used in other languages to navigate objects.

Example 5-16. Accessing the $age variable using this->

 ?php class Cat {   // How old the cat is   var $age;   // Constructor   function Cat($new_age)   {     // Set the age of this cat to the new age     $this->age = $new_age;   }   //The birthday method increments the age variable   function Birthday()   {     $this->age++;   } } // Create a new instance of the cat object that's one year old $fluffy=new Cat(1); echo "Age is $fluffy->age <br/>"; echo "Birthday<br/>"; // Increase fluffy's age $fluffy->Birthday(); echo "Age is $fluffy->age <br/>"; ?> 

Example 5-16 produces:

 Age is 1 Birthday Age is 2 

Notice that you can access the value of $age from outside of the class by using the name of the class instead of this with the -> operator.

5.3.5. Inheritance

When declaring classes, it is also possible to separate functionality into subclasses that automatically inherit the methods and variables of the class on which they are based. This can be useful if you're adding functionality to a class without modifying the original class. Example 5-17 demonstrates how properties and methods are inherited from the parent class for the Domestic_Cat class.

5.3.5.1. The extends operator

When a class inherits from another class, the class that it inherits from is called the superclass. When declaring a subclass, use the extends keyword to specify which class is being inherited from. Example 5-17 shows an example of this.

Example 5-17. Using the extends keyword to define a subclass

 <?php class Cat {   // How old the cat is   var $age;   function Cat($new_age)   {     // Set the age of this cat to the new age     $this->age = $new_age;   }   function Birthday()   {     $this->age++;   } } class Domestic_Cat extends Cat {   // Constructor   function Domestic_Cat() {   }   // Sleep like a domestic cat   function sleep() {   echo("Zzzzzz.<br/>");   } } $fluffy=new Domestic_Cat(); $fluffy->Birthday(); $fluffy->sleep(); echo "Age is $fluffy->age <br>/"; ?> 

Example 5-17 outputs:

 Zzzzzz. Age is 1 

Notice that you can access the Birthday function from the Cat class and the newly defined sleep method regardless of which level in the object defined the method.

5.3.5.2. The parent operator

A Domestic_Cat is a Cat in all respects. It still contains the base methods of a Cat. It's also possible to override existing functionality from the superclass to provide your own new code. When extending classes to override functions in your class that are already defined in the superclass, you can still execute the code from the parent class then add on your own functionality.

To call the parent class method before your code, use:

 parent::method_from_parent 

This calls the parent method in the superclass. You can then add to your code like in Example 5-18.

Example 5-18. Using the parent construct

 <?php class Cat {   // How old the cat is   var $age;   function Cat($new_age)   {     // Set the age of this cat to the new age     $this->age = $new_age;   }   function Birthday()   {     $this->age++;   }   function Eat()   {     echo "Chomp chomp.";   }   function Meow()   {     echo "Meow.";   } } class Domestic_Cat extends Cat {   // Constructor   function Domestic_Cat() {   }   // Eat like a Domestic_Cat   function eat() {     parent::eat();     // After we're finished eating, let's meow     $this->meow();   } } ?> 

This calls the eat function from the superclass, and then adds the code for meowing.

When you extend a class and declare your own constructor, PHP won't automatically call the constructor of the parent class. You should always call the constructor of the parent class to be sure all initialization code gets executed, as shown in Example 5-19.

Example 5-19. Calling the constructor of the parent class

 <?php   class Cat {   // How old the cat is   var $age;   function Cat($new_age)   {     // Set the age of this cat to the new age     $this->age = $new_age;   }   function Birthday()   {     $this->age++;   }   function Eat()   {     echo "Chomp chomp.";   }   function Meow()   {     echo "Meow.";   } } class Domestic_Cat extends Cat {   // Constructor   function Domestic_Cat($new_age) {     // This will call the constructor     // in the parent class (the superclass)     parent::Cat($new_age);   } } ?> 

When a new instance of Domestic_Cat is created, the constructor from the Cat class is called.

5.3.6. Static Methods and Variables

Methods and variables can also be used and accessed as if they are static in a class. Static means the method or variable is accessible through the class definition and not just through objects. In PHP 4, there is no way to designate a variable to be static; however, in PHP 5.0, you can use the static modifier. We'll discuss the syntax that PHP provides to access static values in a class next.

5.3.6.1. The :: operator (scope resolution)

The :: operator allows you to refer to variables and methods on a class that doesn't yet have any instances or objects created for it. When you plan on using the scope resolution operator on a method, you can also detect inside the called function if the method was called using the scope resolution operator (::) or through an object (->) by the $this operator, as shown in Example 5-20.

Example 5-20. Using the -> operator to call hypnotize

 class Hypnotic_Cat extends Cat {   // Constructor   function Hypnotic_Cat() {   }   // This is meant to be called statically   function hypnotize() {   //detects that the function is being called statically   //since a static call doesn't have an object to point to     if ($this == null)       echo ("All cats are hypnotized.");     else     {       echo ("The cat was hypnotized.");       return;     }   } } // Hypnotize all cats Hypnotic_Cat::hypnotize(); $hypnotic_cat = new Hypnotic_Cat(); // Does nothing $hypnotic_cat->hypnotize(); 

When a method is called using the scope resolution operator (::), you can't use the $this object to refer to the object, since there is no object.

5.3.7. Variable References

In PHP, a variable name points to a location in memory that stores the data. There can be more than one variable name pointing to the same spot in memory. The ampersand operator (&) is used to indicate that you're interested in the location in memory that a variable points to instead of its value.

PHP references allow you to create two variables to refer to the same content. Therefore, changing the value of one variable can change the value of another. This can make it very difficult to find errors in your code, since changing one variable also changes the other.

The same syntax can be used with functions that return referencesfor example, using the new operator. Example 5-21 uses this to reference the $some variable.

Example 5-21. Referencing the $some_variable

 <?php $some_variable = "Hello World!"; $some_reference = &$some_variable; $some_reference = "Guten Tag World!"; echo $some_variable; echo $some_reference; ?> 

Example 5-21 outputs:

 Gutentag World!Guten Tag World! 

Example 5-21 shows that a reference is set using the & operator and precedes the $ in the existing variable. The variable $some_reference refers to $some_variable (the memory location where "Hello World!" resides) and any operation, with the exception of setting to another reference, operates on $some_variable.

As discussed earlier, variable references are useful for passing a variable by reference as a parameter to a function. This allows the function to modify the variable in your main code instead of modifying a local copy that's lost when the function completes.

Assigning a variable to another variable without using the reference operator results in a copy of the variable being placed into a new location in memory. The new variable can be changed without modifying the original variable. While this takes more memory, it's the way to go if you don't want to change the original variable's value.

Now that you've learned about functions and classes, you're ready to start working with more complex data, such as arrays. Arrays will be very useful when working with data from a database, since they can easily hold the data from a query.



Learning PHP and MySQL
Learning PHP and MySQL
ISBN: 0596101104
EAN: 2147483647
Year: N/A
Pages: 135

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