Creating a Class


A class is a collection of variables and functionsin OOP terms, properties and methods. A class is a type, and you create objects of that type and store them in PHP variables. We've already seen an example, the Animal class, which we'll dissect here in more detail. You start creating the Animal class with the class statement, giving the new name of this class like this:

 class Animal {         .         .         . } 

This class is supposed to store the name of the animal, so we'll declare an internal variable, called a property in OOP, using the var statementalthough the variable is called $name, the property is actually referred to simply as name:

 class Animal {     var $name;         .         .         . } 

As anywhere else in PHP, you don't have to declare variables you use in a class before you use them. However, when you're working with properties inside a class, you should declare them like this with the var statement, which helps make them accessible from objects you create of this class. Now the data in the name property is available to all the methods in the Animal class, such as the set_name method, which we'll use to set the animal's name:

 class Animal {     var $name;     function set_name($text)     {         .         .         .     }         .         .         . } 

How do you store the name passed to set_name in the name property? To access the $name property, you use the $this built-in variable, which points to the current class. You use $this with the arrow operator, ->, so that you can refer to the data in the name property this way (note this is $this->name for the name property, not $this->$name):

 class Animal {     var $name;     function set_name($text)     {         $this->name = $text;     }         .         .         . } 

Now we've stored the name passed to the set_name method in the name property, we can recover it using the get_name method:

 class Animal {     var $name;     function set_name($text)     {         $this->name = $text;     }     function get_name()     {         return $this->name;     } } 

That's it; we've created the Animal class, which we'll put to work in the next chunk. Note that you can assign simple, constant values to properties when you declare them in a class, but not any kind of computed value:

 class Animal {     var $name = "Leo";  // OK.     var $name = "L" . "e" . "o";  // No good! 

Note also that you can't intermingle the definition of a class with HTML; the entire class definition must be inside the same <?php...?> script. In addition, because PHP has some built-in methods that start with _ _ (two underscores), you shouldn't start any method names with_ _.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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