Page 188 - Open Soource Technologies 304.indd
P. 188
Web Technologies-I
Notes We start out by creating an instance of an Animal class and then call the Greet() function. The
result should be the generic greeting we wrote first. After that, we assign a new instance of
the Dog class to the $animal variable, assign a real name to our dog and then call the Greet()
function again. This time, the Dog specific Greet() function is used and we get a more specific
greeting from our animal, because it is now a dog.
Inheritance works recursively as well you can create a class that inherits from the Dog class,
which in turn inherits from the Animal class, for instance a Puppy class. The Puppy class will
then have variables and methods from both the Dog and the Animal class.
Develop a PHP program for inheritance.
8.5.4 Abstract Classes
Abstract classes are special because they can never be instantiated. Instead, you typically inherit
a set of base functionality from them in a new class. For that reason, they are commonly used
as the base classes in a larger class hierarchy.
A method can be marked as abstract as well. As soon as you mark a class function as
abstract, you have to define the class as abstract as only abstract classes can hold abstract
functions. Another consequence is that you do not have to (and cannot) write any code for
the function it is a declaration only. You would do this to force anyone inheriting from your
abstract class to implement this function and write the proper code for it. If you do not,
PHP will throw an error. However, abstract classes can also contain non-abstract methods,
which allow you to implement basic functionality in the abstract class. Let’s go on with an
example. Here is the abstract class:
abstract class Animal
{
public $name;
public $age;
public function Describe()
{
return $this->name . “, “ . $this->age . “ years old”;
}
abstract public function Greet();
}
As you can see, it looks like a regular exception, but with a couple of differences. The first one
is the abstract keyword, which is used to mark both the class it self and the last function as
abstract. As mentioned, an abstract function cannot contain any body (code), so it is simply
ended with a semicolon as you can see. Now let’s create a class that can inherit our Animal class:
class Dog extends Animal
{
182 LOVELY PROFESSIONAL UNIVERSITY