In PHP5, Zend engine has been rewritten to accomodate the new object oriented concepts. To start with, I will write on some functions that have been added to PHP5’s bag.
~ The access modifiers public/private/protected are introduced for methods and properties.
~ __construct() is used now instead of the function names in the name of the classes which makes it a uniform way of access
~ __destruct() function is now introduced which will run when an object is destroyed
Let us create a class to verify how the above concepts work.
class myBook{
private var $bookTitle;
function __constructor(){
echo "Book object created in constructor";
}
function getBookTitle(){
return $this->bookTitle;
}
function setBookTitle(){
$this->bookTitle = "Hope Wins";
}
function __destruct(){
echo "Object perishes now!";
}
}
$myNewBook = new myBook();
// $myNewBook->bookTitle = "Truth about life";
// The above statement will return an error notice as the variable bookTitle declare private.
$myNewBook->getBookTitle();
$myNewBook = nothing;
unset($myNewBook);
~ Introduction of Abstract classes
An abstract class is a class that cannot be instantiated. But, you can inherit from an abstract class. If you want to declare a method as an abstract method, then you need to declare the class as an abstract class as well. When a method is declared abstract, then the inherting class will implement the method.
abstract class shape{
var $a, $b;
function calcSqFeet($a=0, $b=0){
if(!empty($a) && !empty($b){ echo "Square feet ".$a * $b); }
}
abstract function color();
}
class rectangle extends shape{
var $a, $b;
function __construct($a, $b){
$this->a = $a;
$this->b = $b;
}
function color(){
echo "Color of the shape is :" . "Red";
}
function getSqFeet($a, $b){
return calcSqFeet($a, $b);
}
}
// Declaration
$myShape->color();
$myShape->getSqFeet(3, 4);