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

Unit 8: Objects



                                                                                                  Notes

            class Animal
            {
                public $name;


                public function Greet()
                {
                    return “Hello, I’m some sort of animal and my name is “ . $this->name;

                }
            }
            However, “some sort of animal” is not very descriptive, so let’s create a child class for a dog:
            class Dog extends Animal

            {
            }
            The dog is declared like a regular class, but after that, we use the extends keyword to tell PHP
            that the Dog class should inherit from the Animal class. Right now, our Dog class has the exact
            same functionality as the Animal class. Verify this by running the following code:
            $dog = new Dog();

            echo $dog->Greet();
            You will see that both the name and the Greet() function is still there, but they are also still very
            anonymous. Let’s change that by writing a specific version of the Greet() function for our Dog:
            class Dog extends Animal
            {
                public function Greet()

                {
                    return “Hello, I’m a dog and my name is “ . $this->name;
                }

            }
            Notice that we declare the Greet() function again, because we need for it to do something else,
            but the $name class variable is not declared—we already have that defined on the Animal class,
            which is just fine. As you can see, even though $name is not declared on the Dog class, we can
            still use it in its Greet() function. Now, with both classes declared, it is time to test them out.
            The following code will do that for us:

            $animal = new Animal();
            echo $animal->Greet();
            $animal = new Dog();

            $animal->name = “Bob”;
            echo $animal->Greet();


                                             LOVELY PROFESSIONAL UNIVERSITY                                   181
   182   183   184   185   186   187   188   189   190   191   192