6CC001 Workshop - week 03

From mi-linux
Revision as of 13:41, 11 September 2009 by In9352 (talk | contribs)
Jump to navigationJump to search

Main Page >> Web Application Development >> Workbook >> Week 03

Static classes - An example

class Preferences
{
  private static $values = array();
  
  static function set($key, $val)
  {
    self::$values[$key] = $val;
  }
  
  static function get($key)
  {
    return self::$values[$key];
  }
}
Preferences::set("db_server", "mi-linux");
$db_server = Preferences::get("db_server");
echo $db_server;

Abstract classes - an example

An abstract class cannot be instantiated, i.e. you cannot use the “new” operator to create objects.

An abstract class defines (and optionally partially implements) the interface for any class that might extend it (via inheritance).

abstract class Shape
{
  protected $height;
  protected $width;
  
  public function __construct($height, $width)
  {
    $this->height = $height;
    $this->width = $width;
  }
  
  abstract public function CalculateSurface();
} 

This “Shape” class is telling us:

  • I am abstract, and as such cannot be used directly. I am only a rough template that other classes can build on via inheritance.
  • All my “children” classes will have $height and $width attributes, as well as a standard constructor method.
  • They must also have a CalculateSurface method, but I leave it to them to implement how that bit works.

A first child class could be:

class Rectangle extends Shape
{
  public function CalculateSurface()
  {
    return $this->height * $this->width;
  }
}

This “Rectangle” class is telling us:

  • I wish to extend the Shape class, and as such I inherits the $height and $width attributes, as well as the standard constructor method.
  • Furthermore, and as per “contract”, I provide an implementation for the CalculateSurface method.

Likewise, another child class could be :

class Circle extends Shape
{
  public function __construct($height)
  {
    $this->height = $height;
    $this->width = $height;  
  }
  public function CalculateSurface()
  {
    $radius = $this->height/2;
    return 3.14 * $radius * $radius;
  }
}

This “Circle” class is telling us:

  • I wish to extend the Shape class, but I choose to override the constructor method (since being a circle means my height and width are equal)
  • Furthermore, and as per “contract”, I provide an implementation for the CalculateSurface method.

You can instantiate the Circle and Rectangle classes, as they are not abstract:

$rectangle = New Rectangle(50, 30);
$circle = New Circle(10);

print $rectangle->CalculateSurface()."<br>";
print $circle->CalculateSurface()."<br>";