Page 212 - Beginning PHP 5.3
P. 212

Part II: Learning the Language
                      case Car::STATION_WAGON:
                        echo “station wagon”;
                        break;
                      case Car::SUV:
                        echo “SUV”;
                        break;

                    }
                   In this example, the  Car  class contains three class constants  —  HATCHBACK ,  STATION_WAGON , and  SUV   —

                   that are assigned the values   1 ,  2 , and  3 , respectively. These constants are then used when setting and
                reading the   $type  property of the  $myCar  object.



                  Working with Methods

                   Up to this point, the classes and objects you ’ ve created have mostly consisted of properties. As such,
                 they ’ re not really much use, except as glorified associative arrays. It ’ s when you start adding methods to
                 classes that they become truly powerful. An object then becomes a nicely encapsulated chunk of
                 functionality, containing both data and the methods to work on that data.

                   As mentioned earlier, a method is much like a function, except that it ’ s tied to a specific class.

                  Method Visibility

                   Earlier in the chapter you learned that a property can have three visibility levels: public, private, and
                 protected.

                   The same is true of methods. All methods can be called by other methods within the same class. If a
                 method is declared public, any code outside the class definition can also potentially call the method.
                 However, if a method is declared private, only other methods within the same class can call it. Finally, a
                 protected method can be called by other methods in the class, or in a class that inherits from the class.


                  Creating a Method
                   To add a method to a class, use the  public ,  private , or  protected  keyword, then the  function
                keyword, followed by the method name, followed by parentheses. You then include the method ’ s code
                within curly braces:

                    class MyClass {

                      public function aMethod() {
                        // (do stuff here)
                      }




                    }


                      You can optionally leave out the  public ,  private , or  protected  keyword. If you do this,  public
                    is assumed.

              174





                                                                                                      9/21/09   9:03:33 AM
          c08.indd   174                                                                              9/21/09   9:03:33 AM
          c08.indd   174
   207   208   209   210   211   212   213   214   215   216   217