Page 185 - Open Soource Technologies 304.indd
P. 185

Unit 8: Objects



            $animal = new Animal();                                                               Notes
            With just that line of code, the object will be created, the constructor called and the lines of code
            in it executed, which will cause our “I’m alive!” line to be outputted. However, as mentioned, a
            big advantage of the constructor is the ability to pass parameters which can be used to initialize
            member variables.



            <?php

            class Animal
            {
                public $name = “No-name animal”;
                public function __construct($name)
                {
                    $this->name = $name;

                }
            }
            $animal = new Animal(“Bob the Dog”);
            echo $animal->name;
            ?>
            Declaring the constructor with parameters is just like declaring a regular function, and passing
            the parameter(s) is much like calling a regular function, but of course with the “new” keyword
            that we introduced earlier. A constructor can have as many parameters as you want.
            Destructors
            A destructor is called when the object is destroyed. In some programming languages, you have
            to manually dispose of objects you created, but in PHP, it is handled by the Garbage Collector,
            which keeps an eye on your objects and automatically destroys them when they are no longer
            needed. Have a look at the following example, which is an extended version of our example.




            <?php
            class Animal
            {
                public $name = “No-name animal”;
                public function __construct($name)
                {
                    echo “I’m alive!”;

                    $this->name = $name;
                }
                public function __destruct()
                {





                                             LOVELY PROFESSIONAL UNIVERSITY                                   179
   180   181   182   183   184   185   186   187   188   189   190