Thanks to visit codestin.com
Credit goes to www.slideshare.net

Object-Oriented PHP
1
By: Jalpesh vasa & Sagar Patel
 Topics:
 OOP concepts – overview, throughout the chapter
 Defining and using objects
 Defining and instantiating classes
 Defining and using variables, constants, and operations
 Getters and setters
 Defining and using inheritance and polymorphism
 Building subclasses and overriding operations
 Using interfaces
 Advanced object-oriented functionality in PHP
 Comparing objects, Printing objects,
 Type hinting, Cloning objects,
 Overloading methods, (some sections WILL NOT BE COVERED!!!)
Developing Object-Oriented PHP
2
 Object-oriented programming (OOP) refers to the
creation of reusable software object-types / classes that
can be efficiently developed and easily incorporated into
multiple programs.
 In OOP an object represents an entity in the real world (a
student, a desk, a button, a file, a text input area, a loan, a
web page, a shopping cart).
 An OOP program = a collection of objects that interact to
solve a task / problem.
Object-Oriented Programming
3
 Objects are self-contained, with data and operations that
pertain to them assembled into a single entity.
 In procedural programming data and operations are separate → this
methodology requires sending data to methods!
 Objects have:
 Identity; ex: 2 “OK” buttons, same attributes → separate handle vars
 State → a set of attributes (aka member variables, properties, data
fields) = properties or variables that relate to / describe the object,
with their current values.
 Behavior → a set of operations (aka methods) = actions or
functions that the object can perform to modify itself – its state, or
perform for some external effect / result.
Object-Oriented Programming
4
 Encapsulation (aka data hiding) central in OOP
 = access to data within an object is available only via the object’s
operations (= known as the interface of the object)
 = internal aspects of objects are hidden, wrapped as a birthday
present is wrapped by colorful paper 
 Advantages:
 objects can be used as black-boxes, if their interface is known;
 implementation of an interface can be changed without a
cascading effect to other parts of the project → if the interface
doesn’t change
Object-Oriented Programming
5
 Classes are constructs that define objects of the same type.
A class is a template or blueprint that defines what an
object’s data and methods will be.
Objects of a class have:
 Same operations, behaving the same way
 Same attributes representing the same features, but values of
those attributes (= state) can vary from object to object
 An object is an instance of a class.
(terms objects and instances are used interchangeably)
 Any number of instances of a class can be created.
Object-Oriented Programming
6
Object-Oriented Programming
Defining classes and objects
 Before creating any new object, you need a class or
blueprint of the object. It’s pretty easy to define a new
class in PHP. To define a new class in PHP you use the
class keyword as the following example:
Defining classes and objects
 We’ve defined a new empty class named BankAccount.
From the BankAccount class, we can create new bank
account object using the new keyword as follows:
 Notice that we use var_dump() function to see the content of the bank account.
Properties
 In object-oriented terminology, characteristics of an object
are called properties. For example, the bank account has
account number and total balance. So let’s add those
properties to the BankAccount class:
You see that we used
the private keyword in
front of the properties.
This is called property
visibility. Each property
can have one of three
visibility levels, known
as private, protected
and public.
Property Visibility
 private: private properties of a class only can be accessible
by the methods inside the class. The methods of the class
will be introduced a little later.
 protected: protected properties are similar to the private
properties except that protected properties can be
accessible by the subclasses. You will learn about the
subclasses and inheritance later.
 public: public properties can be accessible not only by the
methods inside but also by the code outside of the class.
Methods
 Behaviors of the object or class are called methods. Similar to the class
properties, the methods can have three different visibility levels: private,
protected, and public.
 With a bank account, we can deposit money, withdraw money and get the
balance. In addition, we need methods to set the bank account number and
get the bank account number. The bank account number is used to
distinguish from one bank account to the other.
 To create a method for a class you use the function keyword followed by
the name and parentheses. A method is similar to a function except that a
method is associated with a class and has a visibility level. Like a
function, a method can have one or more parameter and can return a
value.
Methods
Notice that we used a
special $this variable to access a
property of an object. PHP uses
the $this variable to refer to the
current object.
Methods
Let’s examine the BankAccount's methods in greater detail:
 The deposit() method increases the total balance of the
account.
 The withdraw() method checks the available balance. If the
total balance is less than the amount to be withdrew, it
issues an error message, otherwise it decreases the total
balance.
 The getBalance() method returns the total balance of the
account.
 The setAccountNumber() and getAccountNumber()
methods are called setter/getter methods.
Calling Methods
To call a method of an object, you use the (->) operator
followed by the method name and parentheses. Let’s call the
methods of the bank account class:
PHP Constructor
When you create a new object, it is useful to initialize its
properties e.g., for the bank account object you can set its initial
balance to a specific amount. PHP provides you with a special
method to help initialize object’s properties called constructor.
To add a constructor to a class, you simply add a special method
with the name __construct(). Whenever you create a new object,
PHP searches for this method and calls it automatically.
The following example adds a constructor to the BankAccount
class that initializes account number and an initial amount of
money:
PHP Constructor
PHP Constructor
Now you can create a new bank account object with an account
number and initial amount as follows:
PHP Constructor Overloading
Constructor overloading allows you to create multiple
constructors with the same name __construct() but different
parameters. Constructor overloading enables you to initialize
object’s properties in various ways.
The following example demonstrates the idea of constructor
overloading:
PHP Constructor Overloading
PHP have not yet supported constructor overloading, Oops.
Fortunately, you can achieve the same constructor overloading
effect by using several PHP functions.
PHP Constructor Overloading
PHP Constructor Overloading
How the constructor works.
 First, we get constructor’s arguments using the
func_get_args() function and also get the number of arguments
using the func_num_args() function.
 Second, we check if the init_1() and init_2() method exists
based on the number of constructor’s arguments using the
method_exists() function. If the corresponding method exists,
we call it with an array of arguments using the
call_user_func_array() function.
PHP Destructor
 PHP destructor allows you to clean up resources before PHP
releases the object from the memory. For example, you may
create a file handle in the constructor and you close it in the
destructor.
 To add a destructor to a class, you just simply add a special
method called __destruct() as follows:
PHP Destructor
 There are some important notes regarding the destructor:
 Unlike a constructor, a destructor cannot accept any argument.
 Object’s destructor is called before the object is deleted. It
happens when there is no reference to the object or when the
execution of the script is stopped by the exit() function.
Class unitcounter
{
var $units;
var $weightperunit;
function add($n=1){
$this->units = $this->units+$n;
}
function toatalweight(){
return $this->units * $this->weightperunit;
}
function _ _construct($unitweight=1.0){
$this->weightperunit = $unitweight;
$this->units=0; }
}
$brick = new unitcounter(1.2);
$brick->add(3)
$w1 = $brick->totalweight();
print “total weight of {$brick->units} bricks = $w1”;
Cloning Objects
 A variable assigned with an objects is actually a reference
to the object.
 Copying a object variable in PHP simply creates a second
reference to the same object.
 Example:
$a = new unitcounter();
$a->add(5);
$b=$a;
$b->add(5);
Echo “number of units={$a->units}”;
Echo “number of units={$b->units}”;
//prints number of units = 10
 The _ _clone() method is available, if you want to create
an independent copy of an object.
$a = new unitcounter();
$a->add(5);
$b=$a->_ _clone();
$b->add(5);
Echo “number of units={$a->units}”; //prints 5
Echo “number of units={$b->units}”; //prints 10
Inheritance
 One of most powerful concept of OOP
 Allows a new class to be defined by extending the
capabilities of an existing base class or parent class.
<?php
Require “a1.php”;
Class casecounter extends unitcounter{
var $unitpercase;
function addcase(){
$this->add($this->unitpercase);
}
function casecount() {
return ceil($this->units/$this->unitpercase);
}
function casecounter($casecapacity){
$this->unitpercase = $casecapacity;
}
}
$order = new casecounter(12);
$order->add(7);
$order->addcase();
Print $order->units; // prints 17
Print $order->casecount(); //prints 2
Calling parent constructors
 Instead of writing an entirely new constructor for the
subclass, let's write it by calling the parent's constructor
explicitly and then doing whatever is necessary in addition
for instantiation of the subclass.
Calling a parent class constructor
<?php
Require “a1.php”;
Class casecounter extends unitcounter
{
var $unitpercase;
function addcase()
{
$this->add($this->unitpercase);
}
function casecount()
{
return ceil($this->units/$this->unitpercase);
}
function casecounter($casecapacity, $unitweight)
{
parent::_ _construct($unitweight);
$this->unitpercase = $casecapacity;
}
}
Function overriding
Class shape
{
function info()
{
return “shape”;
}
}
Class polygon extends shape
{
function info()
{
return “polygon”;
}
}
$a = new shape();
$b = new polygon();
Print $a->info(); //prints shape
Print $b->info(); //prints polygon
Function overriding
Class polygon extends shape
{
function info()
{
return parent::info().“.polygon”;
}
}
$b = new polygon();
Print $b->info(); //prints shape.polygon
Reference
https://www.zentut.com/php-tutorial/php-objects-and-classes/
Questions?
Object Oriented PHP - PART-1

Object Oriented PHP - PART-1

  • 1.
  • 2.
     Topics:  OOPconcepts – overview, throughout the chapter  Defining and using objects  Defining and instantiating classes  Defining and using variables, constants, and operations  Getters and setters  Defining and using inheritance and polymorphism  Building subclasses and overriding operations  Using interfaces  Advanced object-oriented functionality in PHP  Comparing objects, Printing objects,  Type hinting, Cloning objects,  Overloading methods, (some sections WILL NOT BE COVERED!!!) Developing Object-Oriented PHP 2
  • 3.
     Object-oriented programming(OOP) refers to the creation of reusable software object-types / classes that can be efficiently developed and easily incorporated into multiple programs.  In OOP an object represents an entity in the real world (a student, a desk, a button, a file, a text input area, a loan, a web page, a shopping cart).  An OOP program = a collection of objects that interact to solve a task / problem. Object-Oriented Programming 3
  • 4.
     Objects areself-contained, with data and operations that pertain to them assembled into a single entity.  In procedural programming data and operations are separate → this methodology requires sending data to methods!  Objects have:  Identity; ex: 2 “OK” buttons, same attributes → separate handle vars  State → a set of attributes (aka member variables, properties, data fields) = properties or variables that relate to / describe the object, with their current values.  Behavior → a set of operations (aka methods) = actions or functions that the object can perform to modify itself – its state, or perform for some external effect / result. Object-Oriented Programming 4
  • 5.
     Encapsulation (akadata hiding) central in OOP  = access to data within an object is available only via the object’s operations (= known as the interface of the object)  = internal aspects of objects are hidden, wrapped as a birthday present is wrapped by colorful paper   Advantages:  objects can be used as black-boxes, if their interface is known;  implementation of an interface can be changed without a cascading effect to other parts of the project → if the interface doesn’t change Object-Oriented Programming 5
  • 6.
     Classes areconstructs that define objects of the same type. A class is a template or blueprint that defines what an object’s data and methods will be. Objects of a class have:  Same operations, behaving the same way  Same attributes representing the same features, but values of those attributes (= state) can vary from object to object  An object is an instance of a class. (terms objects and instances are used interchangeably)  Any number of instances of a class can be created. Object-Oriented Programming 6
  • 7.
  • 8.
    Defining classes andobjects  Before creating any new object, you need a class or blueprint of the object. It’s pretty easy to define a new class in PHP. To define a new class in PHP you use the class keyword as the following example:
  • 9.
    Defining classes andobjects  We’ve defined a new empty class named BankAccount. From the BankAccount class, we can create new bank account object using the new keyword as follows:  Notice that we use var_dump() function to see the content of the bank account.
  • 10.
    Properties  In object-orientedterminology, characteristics of an object are called properties. For example, the bank account has account number and total balance. So let’s add those properties to the BankAccount class: You see that we used the private keyword in front of the properties. This is called property visibility. Each property can have one of three visibility levels, known as private, protected and public.
  • 11.
    Property Visibility  private:private properties of a class only can be accessible by the methods inside the class. The methods of the class will be introduced a little later.  protected: protected properties are similar to the private properties except that protected properties can be accessible by the subclasses. You will learn about the subclasses and inheritance later.  public: public properties can be accessible not only by the methods inside but also by the code outside of the class.
  • 12.
    Methods  Behaviors ofthe object or class are called methods. Similar to the class properties, the methods can have three different visibility levels: private, protected, and public.  With a bank account, we can deposit money, withdraw money and get the balance. In addition, we need methods to set the bank account number and get the bank account number. The bank account number is used to distinguish from one bank account to the other.  To create a method for a class you use the function keyword followed by the name and parentheses. A method is similar to a function except that a method is associated with a class and has a visibility level. Like a function, a method can have one or more parameter and can return a value.
  • 13.
    Methods Notice that weused a special $this variable to access a property of an object. PHP uses the $this variable to refer to the current object.
  • 14.
    Methods Let’s examine theBankAccount's methods in greater detail:  The deposit() method increases the total balance of the account.  The withdraw() method checks the available balance. If the total balance is less than the amount to be withdrew, it issues an error message, otherwise it decreases the total balance.  The getBalance() method returns the total balance of the account.  The setAccountNumber() and getAccountNumber() methods are called setter/getter methods.
  • 15.
    Calling Methods To calla method of an object, you use the (->) operator followed by the method name and parentheses. Let’s call the methods of the bank account class:
  • 16.
    PHP Constructor When youcreate a new object, it is useful to initialize its properties e.g., for the bank account object you can set its initial balance to a specific amount. PHP provides you with a special method to help initialize object’s properties called constructor. To add a constructor to a class, you simply add a special method with the name __construct(). Whenever you create a new object, PHP searches for this method and calls it automatically. The following example adds a constructor to the BankAccount class that initializes account number and an initial amount of money:
  • 17.
  • 18.
    PHP Constructor Now youcan create a new bank account object with an account number and initial amount as follows:
  • 19.
    PHP Constructor Overloading Constructoroverloading allows you to create multiple constructors with the same name __construct() but different parameters. Constructor overloading enables you to initialize object’s properties in various ways. The following example demonstrates the idea of constructor overloading:
  • 20.
    PHP Constructor Overloading PHPhave not yet supported constructor overloading, Oops. Fortunately, you can achieve the same constructor overloading effect by using several PHP functions.
  • 21.
  • 22.
    PHP Constructor Overloading Howthe constructor works.  First, we get constructor’s arguments using the func_get_args() function and also get the number of arguments using the func_num_args() function.  Second, we check if the init_1() and init_2() method exists based on the number of constructor’s arguments using the method_exists() function. If the corresponding method exists, we call it with an array of arguments using the call_user_func_array() function.
  • 23.
    PHP Destructor  PHPdestructor allows you to clean up resources before PHP releases the object from the memory. For example, you may create a file handle in the constructor and you close it in the destructor.  To add a destructor to a class, you just simply add a special method called __destruct() as follows:
  • 24.
    PHP Destructor  Thereare some important notes regarding the destructor:  Unlike a constructor, a destructor cannot accept any argument.  Object’s destructor is called before the object is deleted. It happens when there is no reference to the object or when the execution of the script is stopped by the exit() function.
  • 27.
    Class unitcounter { var $units; var$weightperunit; function add($n=1){ $this->units = $this->units+$n; } function toatalweight(){ return $this->units * $this->weightperunit; } function _ _construct($unitweight=1.0){ $this->weightperunit = $unitweight; $this->units=0; } } $brick = new unitcounter(1.2); $brick->add(3) $w1 = $brick->totalweight(); print “total weight of {$brick->units} bricks = $w1”;
  • 28.
    Cloning Objects  Avariable assigned with an objects is actually a reference to the object.  Copying a object variable in PHP simply creates a second reference to the same object.  Example:
  • 29.
    $a = newunitcounter(); $a->add(5); $b=$a; $b->add(5); Echo “number of units={$a->units}”; Echo “number of units={$b->units}”; //prints number of units = 10
  • 30.
     The __clone() method is available, if you want to create an independent copy of an object. $a = new unitcounter(); $a->add(5); $b=$a->_ _clone(); $b->add(5); Echo “number of units={$a->units}”; //prints 5 Echo “number of units={$b->units}”; //prints 10
  • 31.
    Inheritance  One ofmost powerful concept of OOP  Allows a new class to be defined by extending the capabilities of an existing base class or parent class.
  • 32.
    <?php Require “a1.php”; Class casecounterextends unitcounter{ var $unitpercase; function addcase(){ $this->add($this->unitpercase); } function casecount() { return ceil($this->units/$this->unitpercase); } function casecounter($casecapacity){ $this->unitpercase = $casecapacity; } }
  • 33.
    $order = newcasecounter(12); $order->add(7); $order->addcase(); Print $order->units; // prints 17 Print $order->casecount(); //prints 2
  • 34.
    Calling parent constructors Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass.
  • 36.
    Calling a parentclass constructor <?php Require “a1.php”; Class casecounter extends unitcounter { var $unitpercase; function addcase() { $this->add($this->unitpercase); } function casecount() { return ceil($this->units/$this->unitpercase); } function casecounter($casecapacity, $unitweight) { parent::_ _construct($unitweight); $this->unitpercase = $casecapacity; } }
  • 37.
    Function overriding Class shape { functioninfo() { return “shape”; } } Class polygon extends shape { function info() { return “polygon”; } } $a = new shape(); $b = new polygon(); Print $a->info(); //prints shape Print $b->info(); //prints polygon
  • 38.
    Function overriding Class polygonextends shape { function info() { return parent::info().“.polygon”; } } $b = new polygon(); Print $b->info(); //prints shape.polygon
  • 39.
  • 40.