Initializing Objects with Constructors


As we've already seen, you can use methods such as set_name to assign values to the internal data in an object:

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

However, there's an easy, built-in way to initialize the data in an object when you create that objectyou can use a constructor. In PHP, a constructor is a special method with the name _ _construct (that's two underscores followed by construct), and when you create an object, you can use special syntax to pass data to the constructor.

Here's an example; in this case, we'll add a constructor to the Animal class to set the animal's name, just as the set_name method does. Here's what the constructor looks like:

 function _ _construct($text) {     $this->name = $text; } 

Now when you create the $lion object, you can pass the name of the lion to the Animal class's constructor by using parentheses after the name of the class, like this:

 $lion = new Animal("Leo"); 

That's all you need; now the text "Leo" is passed to the new Animal class constructor, which stores that text in the name property. You can see this code in context in phpconstructor.php.

Example 7-1. Using an object constructor, phpconstructor.php
 <HTML>     <HEAD>         <TITLE>             Reading All Form Data         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Using constructors with objects             </H1>             <?php                 class Animal                 {                     var $name;                     function _ _construct($text)                     {                         $this->name = $text;                     }                     function set_name($text)                     {                         $this->name = $text;                     }                     function get_name()                     {                         return $this->name;                     }                 }                 $lion = new Animal("Leo");                 echo "The name of your new lion is ", $lion->get_name(), ".";             ?>         </CENTER>     </BODY> </HTML> 

The results appear in Figure 7-1, where, as you can see, the data we passed to the constructor was indeed put to work, as we wanted.

Figure 7-1. Using a constructor.


Want to dispose of an object? Use the unset statement like this: unset $object;.



    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