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
Ad

Recommended

Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
Andrey Upadyshev
 
concept of oops
concept of oops
prince sharma
 
Java access modifiers
Java access modifiers
Srinivas Reddy
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
Claudio Capobianco
 
Functions in c++
Functions in c++
Rokonuzzaman Rony
 
Javascript built in String Functions
Javascript built in String Functions
Avanitrambadiya
 
Constructors and Destructors
Constructors and Destructors
Dr Sukhpal Singh Gill
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 
Javascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Introduction to oop
Introduction to oop
colleges
 
Friends function and_classes
Friends function and_classes
asadsardar
 
Php string function
Php string function
Ravi Bhadauria
 
Php array
Php array
Nikul Shah
 
Python-Classes.pptx
Python-Classes.pptx
Karudaiyar Ganapathy
 
C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Oop java
Oop java
Minal Maniar
 
Inline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Object Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Inline function
Inline function
Tech_MX
 
Lect 1-class and object
Lect 1-class and object
Fajar Baskoro
 
Dom
Dom
Rakshita Upadhyay
 
PHP variables
PHP variables
Siddique Ibrahim
 
Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Friend function & friend class
Friend function & friend class
Abhishek Wadhwa
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
P3 InfoTech Solutions Pvt. Ltd.
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
Scope of variables
Scope of variables
baabtra.com - No. 1 supplier of quality freshers
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
Rick Ogden
 
OOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 

More Related Content

What's hot (20)

Javascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Introduction to oop
Introduction to oop
colleges
 
Friends function and_classes
Friends function and_classes
asadsardar
 
Php string function
Php string function
Ravi Bhadauria
 
Php array
Php array
Nikul Shah
 
Python-Classes.pptx
Python-Classes.pptx
Karudaiyar Ganapathy
 
C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Oop java
Oop java
Minal Maniar
 
Inline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Object Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Inline function
Inline function
Tech_MX
 
Lect 1-class and object
Lect 1-class and object
Fajar Baskoro
 
Dom
Dom
Rakshita Upadhyay
 
PHP variables
PHP variables
Siddique Ibrahim
 
Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Friend function & friend class
Friend function & friend class
Abhishek Wadhwa
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
P3 InfoTech Solutions Pvt. Ltd.
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
Scope of variables
Scope of variables
baabtra.com - No. 1 supplier of quality freshers
 

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

(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
Rick Ogden
 
OOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
Introduction Php
Introduction Php
sanjay joshi
 
Basic Oops concept of PHP
Basic Oops concept of PHP
Rohan Sharma
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
Rick Ogden
 
Oops in php
Oops in php
sanjay joshi
 
Oops
Oops
Jaya Kumari
 
Module 4.pptx
Module 4.pptx
charancherry185493
 
Php oop (1)
Php oop (1)
Sudip Simkhada
 
4. Types, Objects and NameSPACES in. Net.pptx
4. Types, Objects and NameSPACES in. Net.pptx
ns1978314
 
Basic OOPs Concepts (E-next.in).pdf
Basic OOPs Concepts (E-next.in).pdf
ShubhamMadaan9
 
Advance oops concepts
Advance oops concepts
Sangharsh agarwal
 
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
 
Oops in PHP
Oops in PHP
Mindfire Solutions
 
My c++
My c++
snathick
 
PHP- Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
Vibrant Technologies & Computers
 
packages and interfaces
packages and interfaces
madhavi patil
 
Object oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
ObjectOrientedSystems.ppt
ObjectOrientedSystems.ppt
ChishaleFriday
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
Rick Ogden
 
OOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
22519 - Client-Side Scripting Language (CSS) chapter 1 notes .pdf
sharvaridhokte
 
Basic Oops concept of PHP
Basic Oops concept of PHP
Rohan Sharma
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
Rick Ogden
 
4. Types, Objects and NameSPACES in. Net.pptx
4. Types, Objects and NameSPACES in. Net.pptx
ns1978314
 
Basic OOPs Concepts (E-next.in).pdf
Basic OOPs Concepts (E-next.in).pdf
ShubhamMadaan9
 
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
 
packages and interfaces
packages and interfaces
madhavi patil
 
Object oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
ObjectOrientedSystems.ppt
ObjectOrientedSystems.ppt
ChishaleFriday
 
Ad

More from Jalpesh Vasa (16)

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

Recently uploaded (20)

Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 

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