Page 189 - Open Soource Technologies 304.indd
P. 189
Unit 8: Objects
public function Greet() Notes
{
return “Woof!”;
}
public function Describe()
{
return parent::Describe() . “, and I’m a dog!”;
}
}
As you can see, we implement both the functions from the Animal class. The Greet() function we
are forced to implement, since it is marked as abstract—it simply returns a word/sound common
to the type of animal we are creating. We are not forced to implement the Describe() function
it is already implemented on the Animal class, but we would like to extend the functionality of
it a bit. Now, the cool part is that we can re-use the code implemented in the Animal class, and
then add to it as we please. In this case, we use the parent keyword to reference the Animal
class, and then we call Describe () function on it. We then add some extra text to the result, to
clarify which type of animal we are dealing with. Now, let’s try using this new class:
$animal = new Dog();
$animal->name = “Bob”;
$animal->age = 7;
echo $animal->Describe();
echo $animal->Greet();
Nothing fancy here, really. We just instantiate the Dog class, set the two properties and then call
the two methods defined on it. If you test this code, you will see that the Describe() method is
now a combination of the Animal and the Dog version, as expected.
8.5.5 Static Classes
Since a class can be instantiated more than once, it means that the values it holds are unique
to the instance/object and not the class itself. This also means that you cannot use methods
or variables on a class without instantiating it first, but there is an exception to this rule. Both
variables and methods on a class can be declared as static (also referred to as “shared” in some
programming languages), which means that they can be used without instantiating the class
first. Since this means that a class variable can be accessed without a specific instance, it also
means that there will only be one version of this variable.
Let’s expand it with some static functionality, to see what the fuzz is all about:
<?php
class User
{
public $name;
public $age;
public static $minimumPasswordLength = 6;
LOVELY PROFESSIONAL UNIVERSITY 183