Login |  Register 
I've learnt so much after subscribing to read your exclusive articles!
Nick
 

Inheritance

Inheritance allows common functionality to be inherited by sub classes. This helps reduce code duplication.

class Base
{
 protected function IsLoggedIn()
 {
  /*
   *
  */
 }
}

class Article extends Base
{
 private $hideContent = false;

 public function ShowContent()
 {
  if ($this->hideContent && !$this->IsLoggedIn())
  {
   return false;
  }
  return true;
 }
}

As you can see the extends keyword is is required for a class to inherit from a base class. A class which extends another gets access to all the protected and public variables and functions.

Overridden

It is possible to override inherited members and methods, by this it means that a function in a super class can be replaced by the inheriting class.

class Article extends Base
{
 private $hideContent = false;

 protected function IsLoggedIn()
 {
  return true;
 }

 public function ShowContent()
 {
  if ($this->hideContent && !$this->IsLoggedIn())
  {
   return false;
  }
  return true;
 }
}

A example of this is shown above where Article overrides the IsLoggedIn function, so that it always returned true.

Class abstraction

This type of class is used specifically for the purposes of inheritance a class marked as abstract can't be instantiated. Furthermore methods can be marked as abstract which forces the inheriting classes to implement them to an equal or a higher visibility.

abstract class Base
{
 protected function IsLoggedIn()
 {
  /*
   *
  */
 }

 abstract protected function IsHTTPSPage();
}

class Article extends Base
{
 private $hideContent = false;

 public function ShowContent()
 {
  if ($this->hideContent && !$this->IsLoggedIn())
  {
   return false;
  }
  return true;
 }

 protected function IsHTTPSPage()
 {
  return false;
 }
}

As shown above the IsHTTPSPage() function had to be implemented by base otherwise a error would have been thrown.


No comments have been provided.
security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38