Introduction to object oriented PHP
Introduction to object oriented PHP
What does OOP aim to achieve?• Allow compartmentalized refactoring of code• Promote code re-use• Promote extensibility, flexibility and adaptability• Better for team development• Many patterns are designed for OOP• Some patterns lead to much more efficient code• Do you need to use OOP to achieve these goals?
– Of course not– It’s designed to make those things easier though
• What are the features of OOP?
–Encapsulation–Inheritance–Polymorphism
Encapsulation• Encapsulation is about grouping of functionality (operations) and related data
(attributes) together into a coherent data structure (classes).• Classes represent complex data types and the operations that act on them. An
object is a particular instance of a class.• An object is an enclosed bundle of variables and functions forged from a special
template called a class.– public anyone can access it– protected only descendants– private only you can access it– final no one can re-declare it– abstract someone else will implement this
• providing instead easy interfaces through which you can send them orders and they can return information. – are special functions called methods. – object have access to special variables called properties
Setting Properties in a Class• Objects have access to special variables called properties.<?php
class Item {
var $name = "item";}$obj1 = new Item();$obj2 = new Item();$obj1->name = "widget 5442";print "$obj1->name<br />";print "$obj2->name<br />";?>
• Static: making them useful when greater flexibility is required.<?phpclass Item { public static $name = "item";}
$obj1 = new Item();$obj2 = new Item();$obj1->name = "koko";$obj2->name="Lola";print "$obj1->name<br />";print "$obj2->name<br />";
?>
EX:<?phpclass ShopProduct {public $title = "default product";public $producerMainName = "main name";public $producerFirstName = "first name";public $price = 0;}$product1 = new ShopProduct();$product2 = new ShopProduct();$product1->title="My Antonia";$product2->title="Catch 22";
?>
Object Methods• A method is a function defined within a class.• public function myMethod( $argument, $another )
{// ...
}• EX1:<?php
class Item {
var $name = "item";function getName() {
return "item"; }} $item = new Item ();print $item->getName ();
?>
EX2:<?php
class Item { var $name = "item"; function getName () { return $this->name;
}}$item = new Item ();$item->name = "widget 5442";print $item->getName ();
?>
EX:<?php
class Item { var $name = "item";
function setName( $n ) { $this->name = $n; }
function getName() { return $this->name; } }
$item = new Item(); $item->setName("widget 5442"); print $item->getName (); // outputs "widget 5442"
?>
<?phpclass Fullname {
private $firstName;private $lastName;public function setFirstName($fName){
$this->firstName=$fName;}public function setLastName($lName){
$this->lastName=$lName;}public function getFirstName(){
return $this->firstName;}public function getLastName(){
return $this->lastName;}}$obj1 = new Fullname();$obj1->setFirstName("Chan");$obj1->setLastName("Dara");print "Full name is " . $obj1->getLastName() . " " . $obj1->getFirstName();
?>
Object Constructors• use a special function called a constructor to set properties and perform any other
preparatory work we require.• A constructor is automatically called when the object is instantiated using the new
keyword.<?php
class Item { private $name; function Item( $name="item") { $this->name = $name; } function setName( $n) { $this->name = $n; } function getName () {
return $this->name; }}$item = new Item("widget 5442");print $item->getName ();?>
<?phpclass Item { private $name; public function __construct() { $this->name = "Chan ty"; } function setName( $n) { $this->name = $n; } function getName () {
return $this->name; }}$item = new Item();print $item->getName ();
?>
<?phpclass Fullname {
private $firstName;private $lastName;public function Fullname(){
$this->firstName="Chan";$this->lastName="Dara";
}public function getLastName(){
return $this->lastName;}public function getFirstName(){
return $this->firstName; }}$obj1 = new Fullname();print "Full name is " . $obj1->getLastName() . " " . $obj1->getFirstName();
?>
Destructor
• The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
• EX: <?php
class MyDestructableClass { function __construct() { print "In constructor\n"; $this->name = "MyDestructableClass"; }
function __destruct() { print "Destroying " . $this->name . "\n"; }}
$obj = new MyDestructableClass();
?>
Inheritance
• Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.
• when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.
• EX:class Humans{
public function __construct($name) { /*...*/}public function eat() { /*...*/ }public function sleep() { /*...*/ }public function snore() { /*...*/ }public function wakeup() { /*...*/ }
}
class Women extends Humans{public function giveBirth() { /*...*/ }
}
EX:<?php
class foo{ public function printItem($string) { echo 'Foo: ' . $string . PHP_EOL; } public function printPHP() { echo 'PHP is great.' . PHP_EOL; }}class bar extends foo{ public function printItem($string) { echo 'Bar: ' . $string . PHP_EOL; }}
$foo = new foo();$bar = new bar();$foo->printItem('baz'); // Output: 'Foo: baz'$foo->printPHP(); // Output: 'PHP is great' $bar->printItem('baz'); // Output: 'Bar: baz'$bar->printPHP(); // Output: 'PHP is great'
?>
<?php class A{ public $publicA; protected $protectedA; private $privateA;function __construct($privateA,$protectedA,$publicA){ $this->privateA=$privateA; $this->protectedA=$protectedA; $this->publicA=$publicA; } protected function setPrivate($privateA){ $this->privateA=$privateA; } protected function getPrivate(){ return $this->privateA; } public function Show(){ echo "A::Show()"; echo $this->privateA; echo $this->protectedA; echo $this->publicA; } }
class B extends A { function __construct($privateA, $protectedA, $publicA) { parent::__construct($privateA, $protectedA, $publicA);} public function Show(){ echo "B::Show()"; //echo $this->privateA; Invalid because it is a private variable echo $this->getPrivate(); echo $this->protectedA; echo $this->publicA; } public function getProtected() { return $this->protectedA; } public function setProtected($protectedA){ $this->protectedA=$protectedA; } }?><?php //Php not support function overload and we have overide default constructor so we can't call like $objA=new A(); $B =new B(2,3,4); $B->Show();//It call Class B Show Function Ouput : B::Show()B::Show()234 // echo $B->protectedA; You can't direct acess protected value echo $B->getProtected(); // Ouput : 3 echo $B->publicA; // Ouput : 4 ?>
EX:class ShopProduct {public $numPages;public $playLength;public $title;public $producerMainName;public $producerFirstName;public $price;function __construct( $title, $firstName,$mainName, $price,$numPages=0, $playLength=0 ) {$this->title = $title;$this->producerFirstName = $firstName;$this->producerMainName = $mainName;$this->price = $price;$this->numPages = $numPages;$this->playLength = $playLength;}function getProducer() {return "{$this->producerFirstName}"." {$this->producerMainName}";}function getSummaryLine() {$base = "$this->title ( {$this->producerMainName}, ";$base .= "{$this->producerFirstName} )";return $base;}}
class CdProduct extends ShopProduct {function getPlayLength() {return $this->playLength;}function getSummaryLine() {$base = "{$this->title} ( {$this->producerMainName}, ";$base .= "{$this->producerFirstName} )";$base .= ": playing time - {$this->playLength}";return $base;}}class BookProduct extends ShopProduct {function getNumberOfPages() {return $this->numPages;}function getSummaryLine() {$base = "{$this->title} ( {$this->producerMainName}, ";$base .= "{$this->producerFirstName} )";$base .= ": page count - {$this->numPages}";return $base;}}$product2 = new CdProduct( "Exile on Coldharbour Lane","The", "Alabama 3",10.99, null, 60.33 );print "artist: {$product2->getProducer()}\n";
EX: Constructors and Inheritanceclass ShopProduct {public $title;public $producerMainName;public $producerFirstName;public $price;function __construct( $title, $firstName,$mainName, $price ) {$this->title = $title;$this->producerFirstName = $firstName;$this->producerMainName = $mainName;$this->price = $price;}function getProducer() {return "{$this->producerFirstName}"." {$this->producerMainName}";}function getSummaryLine() {$base = "{$this->title} ( {$this->producerMainName}, ";$base .= "{$this->producerFirstName} )";return $base;}}
class CdProduct extends ShopProduct {public $playLength;function __construct( $title, $firstName,$mainName, $price, $playLength ) {parent::__construct( $title, $firstName,$mainName, $price );$this->playLength = $playLength;}function getPlayLength() {return $this->playLength;}function getSummaryLine() {$base = "{$this->title} ( {$this->producerMainName}, ";$base .= "{$this->producerFirstName} )";$base .= ": playing time - {$this->playLength}";return $base;}}class BookProduct extends ShopProduct {public $numPages;function __construct( $title, $firstName,$mainName, $price, $numPages ) {parent::__construct( $title, $firstName,$mainName, $price );$this->numPages = $numPages;}function getNumberOfPages() {return $this->numPages;}function getSummaryLine() {$base = "$this->title ( $this->producerMainName, ";$base .= "$this->producerFirstName )";$base .= ": page count - $this->numPages";return $base;}}
EX: Invoking an Overridden Method// ShopProduct class...function getSummaryLine() {$base = "{$this->title} ( {$this->producerMainName}, ";$base .= "{$this->producerFirstName} )";return $base;}// BookProduct class...function getSummaryLine() {$base = parent::getSummaryLine();$base .= ": page count - {$this->numPages}";return $base;}
Polymorphism• A powerful and fundatmental tool, used to create more organic flow in your
application. Pattern in OOP in which classes have different functionality while sharing a common interface.
• An integral part of polymorphism is the common interface. There are two ways to define an interface in PHP: interfaces and abstract classes. Both have their uses, and you can mix and match them as you see fit in your class hierarchy.
Interfaces• An interface is similar to a class except that it cannot contain code. An interface can
define method names and arguments, but not the contents of the methods. Any classes implementing an interface must implement all methods defined by the interface. A class can implement multiple interfaces.
• An interface is declared using the ‘interface‘ keyword:interface Chargeable {public function getPrice();}class ShopProduct implements Chargeable {// ...public function getPrice() {return ( $this->price - $this->discount );}}class Shipping implements Chargeable {public function getPrice() {//...}}
EX:<?phpinterface Chargeable { public function getPrice();}class Employee implements Chargeable { protected $price; public function setPrice($price){
$this->price=price;} public function getPrice() { return $this->price; }}$product = new Employee();$product->setPrice(100);Print getPrice();
?>
EX:<?phpinterface Inter{ const a="This is constant value";
public function disp(); }class A implements Inter{
function show(){
echo self::a."<br/>";}public function disp(){
echo "Inside the disp function";}
}$a=new A();$a->show();$a->disp();?>
Abstraction
• Abstraction facilitates the easy conceptualization of real world object by eliminating the unnecessary detail of the object.
• An abstract class is a mix between an interface and a class. It can define functionality as well as interface (in the form of abstract methods). Classes extending an abstract class must implement all of the abstract methods defined in the abstract class.
• An abstract class is declared the same way as classes with the addition of the ‘abstract‘ keyword:
• EX:abstract class ShopProductWriter {protected $products = array();public function addProduct( ShopProduct $shopProduct ) {$this->products[]=$shopProduct;}}$writer = new ShopProductWriter();// output:// Fatal error: Cannot instantiate abstract class// shopproductwriter ...
EX:<?phpabstract class AbstractClass{ // Force Extending class to define this method abstract protected function getValue(); abstract protected function prefixValue($prefix); // Common method public function printOut() { print $this->getValue() . "\n";}}
class ConcreteClass1 extends AbstractClass{ protected function getValue() { return "ConcreteClass1";} public function prefixValue($prefix) { return "{$prefix}ConcreteClass1";}}
class ConcreteClass2 extends AbstractClass{ public function getValue() { return "ConcreteClass2";}
public function prefixValue($prefix) { return "{$prefix}ConcreteClass2";}}
$class1 = new ConcreteClass1;$class1->printOut();echo $class1->prefixValue('FOO_') ."\n";$class2 = new ConcreteClass2;$class2->printOut();echo $class2->prefixValue('FOO_') ."\n";?>
EX:<?php
abstract class One{
public function disp(){
echo "Inside the parent class<br/>";}}class Two extends One{public function disp(){echo "Inside the child class<br/>";}}class Three extends One{//no method is declared}$two=new Two();echo "<b>Calling from the child class Two:</b><br/>";$two->disp();echo "<b>Calling from the child class Three:</b><br/>";$three=new Three();$three->disp(); ?>