Working with Classes and Objects


So how does this work in practice? First, you create a class, from which to create objects. A class is an object's type, just as integer might be a variable's type, and you can create your own classes. You might create a class named Animal, using the PHP class statement. This class might store the name of the animal internally, and it might have two functions (inside a class, functions are called methods) built into it: set_name and get_name. Here's what the class named Animal looks like (we'll dissect what's going on here in the first couple of chunks in this chapter). Note that this class stores the name data in an internal variable (called a property in OOP) called name:

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

Now you can create objects of this new class with the new statementfor example, you might want to create an object named $lion. Objects such as these are stored in variables in PHP. After you create that object, you can access the get_name and set_name methods using the arrow operator, ->. Here's what that looks like:

 <?php     class Animal     {         var $name;         function set_name($text)         {             $this->name = $text;         }         function get_name()         {             return $this->name;         }     }     $lion = new Animal;     $lion->set_name("Leo");     echo "The name of your new lion is ", $lion->get_name(), "."; ?> 

When you run this code, you get:

 The name of your new lion is Leo. 

We're going to take this apart in the pages to come to understand exactly what's going on here.

Besides OOP, this chapter also focuses on working with files. Being able to work with files on the server is one of the great things about PHP. For example, you might want to create a guest book page on your web site; you could do that by storing the guest book's details in a file. We'll see how to create, open, write to, and read from files in this chapter. Being able to store data on the server is one of the main reasons people turn to server scripts in the first place, and PHP gives you a lot of power here.



    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