SlideShare a Scribd company logo
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.
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
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.
Object Oriented PHP - PART-1
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

More Related Content

What's hot (20)

PDF
Constructors in Java (2).pdf
kumari36
 
PPTX
Java literals
myrajendra
 
PPTX
Java Method, Static Block
Infoviaan Technologies
 
PPTX
Constructors and Destructors
Keyur Vadodariya
 
PPT
Array in Java
Shehrevar Davierwala
 
PPTX
Arrays in c language
tanmaymodi4
 
PPT
Shell programming
Moayad Moawiah
 
PPT
Access Protection
myrajendra
 
PPT
Switch statements in Java
Jin Castor
 
PPTX
Class 10
SIVASHANKARIRAJAN
 
PPTX
I/O Streams
Ravi Chythanya
 
PPT
Taking User Input in Java
Eftakhairul Islam
 
PPSX
Collections - Array List
Hitesh-Java
 
PDF
Lambdas and Streams Master Class Part 2
José Paumard
 
PPSX
C# - Part 1
Md. Mahedee Hasan
 
PPTX
Top 10 python ide
Saravanakumar viswanathan
 
PPTX
constructor with default arguments and dynamic initialization of objects
Kanhaiya Saxena
 
PPTX
function, storage class and array and strings
Rai University
 
PPTX
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Smit Shah
 
PPTX
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
Constructors in Java (2).pdf
kumari36
 
Java literals
myrajendra
 
Java Method, Static Block
Infoviaan Technologies
 
Constructors and Destructors
Keyur Vadodariya
 
Array in Java
Shehrevar Davierwala
 
Arrays in c language
tanmaymodi4
 
Shell programming
Moayad Moawiah
 
Access Protection
myrajendra
 
Switch statements in Java
Jin Castor
 
I/O Streams
Ravi Chythanya
 
Taking User Input in Java
Eftakhairul Islam
 
Collections - Array List
Hitesh-Java
 
Lambdas and Streams Master Class Part 2
José Paumard
 
C# - Part 1
Md. Mahedee Hasan
 
Top 10 python ide
Saravanakumar viswanathan
 
constructor with default arguments and dynamic initialization of objects
Kanhaiya Saxena
 
function, storage class and array and strings
Rai University
 
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Smit Shah
 
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 

Similar to Object Oriented PHP - PART-1 (20)

PPT
PHP- Introduction to Object Oriented PHP
Vibrant Technologies & Computers
 
PPTX
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
DOCX
Oops concept in php
selvabalaji k
 
PDF
OOP in PHP
Tarek Mahmud Apu
 
PPTX
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
PPTX
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
PPTX
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
PDF
09 Object Oriented Programming in PHP #burningkeyboards
Denis Ristic
 
PPTX
Oopsinphp
NithyaNithyav
 
PPTX
Ch8(oop)
Chhom Karath
 
PPTX
Only oop
anitarooge
 
PPTX
Object oreinted php | OOPs
Ravi Bhadauria
 
PPTX
Object oriented programming in php
Aashiq Kuchey
 
PPTX
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
 
PPTX
Php oop (1)
Sudip Simkhada
 
PPT
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
PPT
Advanced php
hamfu
 
PPT
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
PPT
Oop in php lecture 2
Mudasir Syed
 
PHP- Introduction to Object Oriented PHP
Vibrant Technologies & Computers
 
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Oops concept in php
selvabalaji k
 
OOP in PHP
Tarek Mahmud Apu
 
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
09 Object Oriented Programming in PHP #burningkeyboards
Denis Ristic
 
Oopsinphp
NithyaNithyav
 
Ch8(oop)
Chhom Karath
 
Only oop
anitarooge
 
Object oreinted php | OOPs
Ravi Bhadauria
 
Object oriented programming in php
Aashiq Kuchey
 
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
 
Php oop (1)
Sudip Simkhada
 
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Advanced php
hamfu
 
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
Oop in php lecture 2
Mudasir Syed
 
Ad

More from Jalpesh Vasa (16)

PDF
Object Oriented PHP - PART-2
Jalpesh Vasa
 
PDF
5. HTML5
Jalpesh Vasa
 
PDF
4.4 PHP Session
Jalpesh Vasa
 
PDF
4.3 MySQL + PHP
Jalpesh Vasa
 
PDF
4.2 PHP Function
Jalpesh Vasa
 
PDF
4.1 PHP Arrays
Jalpesh Vasa
 
PDF
4 Basic PHP
Jalpesh Vasa
 
PDF
3.2.1 javascript regex example
Jalpesh Vasa
 
PDF
3.2 javascript regex
Jalpesh Vasa
 
PDF
3. Java Script
Jalpesh Vasa
 
PDF
3.1 javascript objects_DOM
Jalpesh Vasa
 
PDF
2 introduction css
Jalpesh Vasa
 
PDF
1 web technologies
Jalpesh Vasa
 
PDF
Remote Method Invocation in JAVA
Jalpesh Vasa
 
PDF
Kotlin for android development
Jalpesh Vasa
 
PDF
Security in php
Jalpesh Vasa
 
Object Oriented PHP - PART-2
Jalpesh Vasa
 
5. HTML5
Jalpesh Vasa
 
4.4 PHP Session
Jalpesh Vasa
 
4.3 MySQL + PHP
Jalpesh Vasa
 
4.2 PHP Function
Jalpesh Vasa
 
4.1 PHP Arrays
Jalpesh Vasa
 
4 Basic PHP
Jalpesh Vasa
 
3.2.1 javascript regex example
Jalpesh Vasa
 
3.2 javascript regex
Jalpesh Vasa
 
3. Java Script
Jalpesh Vasa
 
3.1 javascript objects_DOM
Jalpesh Vasa
 
2 introduction css
Jalpesh Vasa
 
1 web technologies
Jalpesh Vasa
 
Remote Method Invocation in JAVA
Jalpesh Vasa
 
Kotlin for android development
Jalpesh Vasa
 
Security in php
Jalpesh Vasa
 
Ad

Recently uploaded (20)

PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 

Object Oriented PHP - PART-1

  • 2.  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
  • 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 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
  • 5.  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
  • 6.  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
  • 8. 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:
  • 9. 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.
  • 10. 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.
  • 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 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.
  • 13. 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.
  • 14. 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.
  • 15. 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:
  • 16. 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:
  • 18. PHP Constructor Now you can create a new bank account object with an account number and initial amount as follows:
  • 19. 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:
  • 20. 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.
  • 22. 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.
  • 23. 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:
  • 24. 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.
  • 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  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:
  • 29. $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
  • 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 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.
  • 32. <?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; } }
  • 33. $order = new casecounter(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 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; } }
  • 37. 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
  • 38. Function overriding Class polygon extends shape { function info() { return parent::info().“.polygon”; } } $b = new polygon(); Print $b->info(); //prints shape.polygon