PHP: Important Object Oriented Snippet
class Person {
private $name;
private $job;
//constructor. If no argument, then both $name and $job is null
public function __construct($name, $job){
$this->name = $name;
$this->job = $job;
}
//destructor
public function __destruct() {
print "Destroying object";
}
public function communicate($style = 'voice'){
return 'communicating with' . $style;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
function __clone() {
print "Object is being cloned";
}
}
$p = new Person('John', 'Teacher');
echo $p->communicate('telepathy');
$p\_copy = clone $p; //\_\_clone() will be called
// Static
class MyClass {
static $myStaticVariable;
static $myInitializedStaticVariable = 0;
static const SUCCESS = "Success";
static const FAILURE = "Failure";
function myMethod() //self is like this
{
print self::$myInitializedStaticVariable;
}
static function helloWorld() {
print "Hello, world";
}
}
//outside of the class, use ClassName::
MyClass::$myInitializedStaticVariable++;
print MyClass::$myInitializedStaticVariable;
MyClass::helloWorld();
//Polymorphism
//This is Inefficient
function printTheRightSound($obj)
{
if ($obj instanceof Cat) {
$obj->miau();
} else if ($obj instanceof Dog) {
$obj->wuff();
} else {
print "Error: Passed wrong kind of object";
}
print "\\n";
}
//Efficient:
class Animal {
private $born_date;
private $die_date;
function __construct(){
$this->born_date = date("format");
print $born_date;
}
function __destruct(){
$this->die_date = date("format");
print $die_date;
}
function makeSound()
{
print "Error: This method should be re-implemented in the children";
}
}
class Cat extends Animal {
function __construct(){
parent::__construct();
print "In SubClass constructor\\n";
}
function makeSound()
{
print "miau";
}
}
class Dog extends Animal {
function __construct(){
parent::__construct();
print "In SubClass constructor\\n";
}
function makeSound()
{
print "wuff";
}
}
function printTheRightSound($obj)
{
if ($obj instanceof Animal) {
$obj->makeSound();
} else {
print "Error: Passed wrong kind of object";
}
print "\\n";
}
// if there's abstract method, then the class must be abstract
abstract class Shape {
function setCenter($x, $y) {
$this->x = $x;
$this->y = $y;
}
abstract function draw();
protected $x, $y;
}
class Square extends Shape {
function draw()
{
// Here goes the code which draws the Square
//...
}
}
class Circle extends Shape {
function draw()
{
// Here goes the code which draws the Circle
//...
}
}
/\*Interfaces. A class can inherit only from one class, but may implement as many interfaces as it wants \*/
// interface only contain the method definition. No bodies
// Interfaces are always considered to be public;
// you can’t specify access modifiers for the method prototypes in the interface’s declaration.
// You may not implement multiple interfaces that clash with each other
// (for example, interfaces that define the same constants or methods).
interface Display {
function display();
}
interface Round {
function circumference();
}
class Circle implements Display, Round {
function display() {
print "Displaying circle\\n";
}
function circumference(){
print "Calculating Circumference";
}
}
if ($obj instanceof Circle) {
print '$obj is a Circle';
}
interface Loggable {
function logString();
}
class Person implements Loggable {
private $name, $address, $idNumber, $age;
function logString() {
return "class Person: name = $this->name, ID = $this->idNumber\\n";
}
}
class Product implements Loggable {
private $name, $price, $expiryDate;
function logString() {
return "class Product: name = $this->name, price = $this->price\\n";
}
}
function MyLog($obj) {
if ($obj instanceof Loggable) {
print $obj->logString();
} else {
print "Error: Object doesn’t support Loggable interface\\n";
}
}
// final access modifier for methods that declares the method as
// the final version, which can’t be overridden.
// Final class, can't be inherited
class MyClass {
final function getBaseClassName() {
return \_\_CLASS\_\_;
}
}
// MyIteratorImplementation() so the object can be iterated using foreach
$obj = new MyIteratorImplementation();
foreach ($obj as $value) {
print "$value";
}
// Many developers writing object-oriented applications create one PHP
// source file per class definition. One of the biggest annoyances
// is having to write a long list of needed inclusions at the beginning
// of each script (one for each class). In PHP 5, this is no longer necessary.
// You may define an __autoload() function that is automatically called in case
// you are trying to use a class that has not been defined yet. By calling this function,
// the scripting engine offers one last chance to load the class before PHP bails out with an error:
// http://php.net/manual/en/language.oop5.autoload.php
function \_\_autoload($class\_name) {
include\_once($class\_name . "php");
}
class SQLException extends Exception {
public $problem;
function __construct($problem) {
$this->problem = $problem;
}
}
try {
...
throw new SQLException("Couldn't connect to database");
...
} catch (SQLException $e) {
print "Caught an SQLException with problem $obj->problem";
} catch (Exception $e) {
print "Caught unrecognized exception";
}
//Casting Associative Array as Object
$series = array('first' => 1,
'second' => 2,
'third' => 3,
'fourth' => 4);
$obj = (object)$series;
print($obj->first . "\\n"); //1
print($obj->second . "\\n"); //2