SlideShare a Scribd company logo
PHP Object Oriented
Programming (OOP)
Dr. Charles Severance
www.wa4e.com
http://www.wa4e.com/code/objects.zip
PHP => Object Oriented
• With PHP 5, an object oriented approach is the preferred
pattern.
• Libraries are evolving toward OOP.
Object Oriented Programming
(OOP)
Object-oriented programming (OOP) is a programming
paradigm that represents concepts as "objects" that
have data fields (attributes that describe the object) and
associated procedures known as methods. Objects,
which are usually instances of classes, are used to
interact with one another to design applications and
computer programs.
http://en.wikipedia.org/wiki/Object-oriented_programming
Definitions
• Class - a template - Dog
• Method - A defined capability of a class - bark()
• Object or Instance - A particular instance of a class -
Lassie
Image CC-By 2.0: https://www.flickr.com/photos/dinnerseries/235704750
Terminology: Class
Defines the abstract characteristics of a thing (object), including
the thing’s characteristics (its attributes, fields, or properties)
and the thing’s behaviors (the things it can do, or methods,
operations, or features). One might say that a class is a
blueprint or factory that describes the nature of something. For
example, the class Dog would consist of traits shared by all
dogs, such as breed and fur color (characteristics), and the
ability to bark and sit (behaviors).
Terminology: Instance
One can have an instance of a class or a particular object.
The instance is the actual object created at runtime. In
programmer jargon, the Lassie object is an instance of
the Dog class. The set of values of the attributes of a
particular object is called its state. The object consists of
state and the behavior that is defined in the object’s class.
Object and Instance are often used interchangeably.
Terminology: Method
An object’s abilities. In language, methods are verbs. Lassie,
being a Dog, has the ability to bark. So bark() is one of Lassie’s
methods. She may have other methods as well, for example
sit() or eat() or walk() or save_timmy(). Within the program,
using a method usually affects only one particular object; all
Dogs can bark, but you need only one particular dog to do the
barking.
Method and Message are often used interchangeably.
http://php.net/manual/en/ref.datetime.php
Non-OOP
http://www.php.net/manual/en/class.datetime.php
OOP
<?php
date_default_timezone_set('America/New_York');
$nextWeek = time() + (7 * 24 * 60 * 60);
echo 'Now: '. date('Y-m-d') ."n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."n";
echo("=====n");
$now = new DateTime();
$nextWeek = new DateTime('today +1 week');
echo 'Now: '. $now->format('Y-m-d') ."n";
echo 'Next Week: '. $nextWeek->format('Y-m-d') ."n";
Now: 2013-09-25
Next Week: 2013-10-02
=====
Now: 2013-09-25
Next Week: 2013-10-02
date.php
Making a Class / Objects
<?php
$chuck = array("fullname" => "Chuck Severance",
'room' => '4429NQ');
$colleen = array("familyname" => "van Lent",
'givenname' => 'Colleen', 'room' => '3439NQ');
function get_person_name($person) {
if ( isset($person['fullname']) ) return $person['fullname'];
if ( isset($person['familyname']) && isset($person['givenname']) ) {
return $person['givenname'] . ' ' . $person['familyname'] ;
}
return false;
}
print get_person_name($chuck) . "n";
print get_person_name($colleen) . "n";
Chuck Severance
Colleen van Lent
nonobj.php
<?php
class Person {
public $fullname = false;
public $givenname = false;
public $familyname = false;
public $room = false;
function get_name() {
if ( $this->fullname !== false ) return $this->fullname;
if ( $this->familyname !== false && $this->givenname !== false ) {
return $this->givenname . ' ' . $this->familyname;
}
return false;
}
}
$chuck = new Person();
$chuck->fullname = "Chuck Severance";
$chuck->room = "4429NQ";
$colleen = new Person();
$colleen->familyname = 'van Lent';
$colleen->givenname = 'Colleen';
$colleen->room = '3439NQ';
print $chuck->get_name() . "n";
print $colleen->get_name() . "n";
Chuck Severance
Colleen van Lent
withobj.php
Reading Documentation
Two New Operators
• Access “static item” in a class
echo DateTime::RFC822."n";
• Access item in an object
echo $z->format('Y-m-d')."n";
echo DateTime::RFC822."n";
D, d M y H:i:s O
$x = new DateTime();
$y = new DateTime('now');
$z = new DateTime('2012-01-31');
$x = new DateTime('1999-04-31');
$oops = DateTime::getLastErrors();
print_r($oops);
Array
(
[warning_count] => 1
[warnings] => Array
(
[11] => The parsed date was invalid
)
[error_count] => 0
[errors] => Array
(
)
)
$z = new DateTime('2012-01-31');
echo $z->format('Y-m-d')."n";
2012-01-31
http://php.net/manual/en/language.oop5.magic.php
Object Life Cycle
http://en.wikipedia.org/wiki/Constructor_(computer_science)
Object Life Cycle
• Objects are created, used and discarded.
• We have special blocks of code (methods) that get called
- At the moment of creation (constructor)
- At the moment of destruction (destructor)
• Constructors are used a lot.
• Destructors are seldom used.
Constructor
The primary purpose of the constructor is to set up some
instance variables to have the proper initial values when the
object is created.
class PartyAnimal {
function __construct() {
echo("Constructedn");
}
function something() {
echo("Somethingn");
}
function __destruct() {
echo("Destructedn");
}
}
echo("--Onen");
$x = new PartyAnimal();
echo("--Twon");
$y = new PartyAnimal();
echo("--Threen");
$x->something();
echo("--The End?n");
--One
Constructed
--Two
Constructed
--Three
Something
--The End?
Destructed
Destructed
party.php
Many Instances
• We can create lots of objects - the class is the template
for the object.
• We can store each distinct object in its own variable.
• We call this having multiple instances of the same class.
• Each instance has its own copy of the instance variables.
class Hello {
protected $lang; // Only accessible in the class
function __construct($lang) {
$this->lang = $lang;
}
function greet() {
if ( $this->lang == 'fr' ) return 'Bonjour';
if ( $this->lang == 'es' ) return 'Hola';
return 'Hello';
}
}
$hi = new Hello('es');
echo $hi->greet()."n";
Hola
hello.php
Definitions
• Class - a template - Dog
• Method or Message - A defined capability of a class -
bark()
• Object or Instance - A particular instance of a class -
Lassie
• Constructor - A method which is called when the
instance / object is created
Inheritance
http://www.php.net/manual/en/language.oop5.inheritance.php
Inheritance
• When we make a new class we can reuse an existing
class and inherit all the capabilities of an existing class
and then add our own little bit to make our new class
• Another form of store and reuse
• Write once - reuse many times
• The new class (child) has all the capabilities of the old
class (parent) - and then some more
Terminology:
Inheritance
http://en.wikipedia.org/wiki/Object-oriented_programming
“Subclasses” are more specialized versions of a class, which
inherit attributes and behaviors from their parent classes, and
can introduce their own.
class Hello {
protected $lang;
function __construct($lang) { ... }
function greet() { ... }
}
class Social extends Hello {
function bye() {
if ( $this->lang == 'fr' ) return 'Au revoir';
if ( $this->lang == 'es' ) return 'Adios';
return 'goodbye';
}
}
$hi = new Social('es');
echo $hi->greet()."n";
echo $hi->bye()."n";
Hola
Adios
goodbye.php
Definitions
• Class - a template - Dog
• Method or Message - A defined capability of a class -
bark()
• Object or Instance - A particular instance of a class -
Lassie
• Constructor - A method which is called when the instance
/ object is created
• Inheritance - the ability to take a class and extend it to
make a new class
Visibility
Class member variables also have scope.
• Public – can be accessed outside the class, inside the
class, and in derived classes
• Protected – can be accessed inside the class, and in
derived classes
• Private – can only be accessed inside the class (i.e. private
variables are not visible in derived classes)
http://www.php.net/manual/en/language.oop5.visibility.php
class MyClass
{
public $pub = 'Public';
protected $pro = 'Protected';
private $priv = 'Private';
function printHello()
{
echo $this->pub."n";
echo $this->pro."n";
echo $this->priv."n";
}
}
$obj = new MyClass();
echo $obj->pub."n"; // Works
echo $obj->pro."n"; // Fatal Error
echo $obj->priv."n"; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
Public
Public
Protected
Private
visibility.php
class MyClass2 extends MyClass
{
function printHello()
{
echo $this->pub."n";
echo $this->pro."n";
echo $this->priv."n"; // Undefined
}
}
echo("--- MyClass2 ---n");
$obj2 = new MyClass2();
echo $obj2->pub."n"; // Works
$obj2->printHello(); // Shows Public, Protected, Undefined
--- MyClass2 ---
Public
Public
Protected
(false)
Building an Object from
Scratch
• Sometimes a developer will prefer to make an object with
public key-value pairs rather than an array.
• Use where appropriate…
$player = new stdClass();
$player->name = "Chuck";
$player->score = 0;
$player->score++;
print_r($player);
class Player {
public $name = "Sally";
public $score = 0;
}
$p2 = new Player();
$p2->score++;
print_r($p2);
stdClass Object
(
[name] => Chuck
[score] => 1
)
Player Object
(
[name] => Sally
[score] => 1
)
scratch.php
Summary
• Object Oriented programming is a very structured approach to
code reuse.
• There is a trend away from global function names and toward
OO.
• We can group data and functionality together and create
many independent instances of a class.
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
(www.dr-chuck.com) as part of www.wa4e.com and made
available under a Creative Commons Attribution 4.0 License.
Please maintain this last slide in all copies of the document to
comply with the attribution requirements of the license. If you
make a change, feel free to add your name and organization
to the list of contributors on this page as you republish the
materials.
Initial Development: Charles Severance, University of Michigan
School of Information
Insert new Contributors and Translators here including names
and dates
Continue new Contributors and Translators here
Additional Source Information
• Snowman Cookie Cutter" by Didriks is licensed under CC BY
https://www.flickr.com/photos/dinnerseries/23570475099
• Photo from the television program Lassie. Lassie watches as Jeff (Tommy Rettig) works on his bike is Public
Domain
https://en.wikipedia.org/wiki/Lassie#/media/File:Lassie_and_Tommy_Rettig_1956.JPG

More Related Content

Similar to PHP-05-Objects.ppt

Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
Alena Holligan
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
Alena Holligan
 
JS-02-JavaScript-Objects.ppt
JS-02-JavaScript-Objects.pptJS-02-JavaScript-Objects.ppt
JS-02-JavaScript-Objects.ppt
MadhukarReddy74
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
Alena Holligan
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
Only oop
Only oopOnly oop
Only oop
anitarooge
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
Alena Holligan
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
Alena Holligan
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
switipatel4
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
Alena Holligan
 
OOP Adventures with XOOPS
OOP Adventures with XOOPSOOP Adventures with XOOPS
OOP Adventures with XOOPS
xoopsproject
 
Oops in php
Oops in phpOops in php
Oops in php
sanjay joshi
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
Rohan Sharma
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Alena Holligan
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comtutorialsruby
 
Oop in php tutorial
Oop in php tutorialOop in php tutorial
Oop in php tutorial
Gua Syed Al Yahya
 

Similar to PHP-05-Objects.ppt (20)

Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
JS-02-JavaScript-Objects.ppt
JS-02-JavaScript-Objects.pptJS-02-JavaScript-Objects.ppt
JS-02-JavaScript-Objects.ppt
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
OOPs Concept
OOPs ConceptOOPs Concept
OOPs Concept
 
Only oop
Only oopOnly oop
Only oop
 
Oops concept in php
Oops concept in phpOops concept in php
Oops concept in php
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
OOP Adventures with XOOPS
OOP Adventures with XOOPSOOP Adventures with XOOPS
OOP Adventures with XOOPS
 
Oops in php
Oops in phpOops in php
Oops in php
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
oop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.com
 
Oop in php tutorial
Oop in php tutorialOop in php tutorial
Oop in php tutorial
 

More from rani marri

NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
rani marri
 
must.pptx
must.pptxmust.pptx
must.pptx
rani marri
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
rani marri
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
rani marri
 
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.pptADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
rani marri
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
data structures module I & II.pptx
data structures module I & II.pptxdata structures module I & II.pptx
data structures module I & II.pptx
rani marri
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
NodeJS.ppt
NodeJS.pptNodeJS.ppt
NodeJS.ppt
rani marri
 
J2EEFeb11 (1).ppt
J2EEFeb11 (1).pptJ2EEFeb11 (1).ppt
J2EEFeb11 (1).ppt
rani marri
 
CODING QUESTIONS.pptx
CODING QUESTIONS.pptxCODING QUESTIONS.pptx
CODING QUESTIONS.pptx
rani marri
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
rani marri
 

More from rani marri (17)

NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
 
must.pptx
must.pptxmust.pptx
must.pptx
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
 
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.pptADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
 
data structures module I & II.pptx
data structures module I & II.pptxdata structures module I & II.pptx
data structures module I & II.pptx
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
NodeJS.ppt
NodeJS.pptNodeJS.ppt
NodeJS.ppt
 
J2EEFeb11 (1).ppt
J2EEFeb11 (1).pptJ2EEFeb11 (1).ppt
J2EEFeb11 (1).ppt
 
CODING QUESTIONS.pptx
CODING QUESTIONS.pptxCODING QUESTIONS.pptx
CODING QUESTIONS.pptx
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
 

Recently uploaded

Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 

Recently uploaded (20)

Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 

PHP-05-Objects.ppt

  • 1. PHP Object Oriented Programming (OOP) Dr. Charles Severance www.wa4e.com http://www.wa4e.com/code/objects.zip
  • 2. PHP => Object Oriented • With PHP 5, an object oriented approach is the preferred pattern. • Libraries are evolving toward OOP.
  • 3. Object Oriented Programming (OOP) Object-oriented programming (OOP) is a programming paradigm that represents concepts as "objects" that have data fields (attributes that describe the object) and associated procedures known as methods. Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs. http://en.wikipedia.org/wiki/Object-oriented_programming
  • 4. Definitions • Class - a template - Dog • Method - A defined capability of a class - bark() • Object or Instance - A particular instance of a class - Lassie Image CC-By 2.0: https://www.flickr.com/photos/dinnerseries/235704750
  • 5. Terminology: Class Defines the abstract characteristics of a thing (object), including the thing’s characteristics (its attributes, fields, or properties) and the thing’s behaviors (the things it can do, or methods, operations, or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors).
  • 6. Terminology: Instance One can have an instance of a class or a particular object. The instance is the actual object created at runtime. In programmer jargon, the Lassie object is an instance of the Dog class. The set of values of the attributes of a particular object is called its state. The object consists of state and the behavior that is defined in the object’s class. Object and Instance are often used interchangeably.
  • 7. Terminology: Method An object’s abilities. In language, methods are verbs. Lassie, being a Dog, has the ability to bark. So bark() is one of Lassie’s methods. She may have other methods as well, for example sit() or eat() or walk() or save_timmy(). Within the program, using a method usually affects only one particular object; all Dogs can bark, but you need only one particular dog to do the barking. Method and Message are often used interchangeably.
  • 10. <?php date_default_timezone_set('America/New_York'); $nextWeek = time() + (7 * 24 * 60 * 60); echo 'Now: '. date('Y-m-d') ."n"; echo 'Next Week: '. date('Y-m-d', $nextWeek) ."n"; echo("=====n"); $now = new DateTime(); $nextWeek = new DateTime('today +1 week'); echo 'Now: '. $now->format('Y-m-d') ."n"; echo 'Next Week: '. $nextWeek->format('Y-m-d') ."n"; Now: 2013-09-25 Next Week: 2013-10-02 ===== Now: 2013-09-25 Next Week: 2013-10-02 date.php
  • 11. Making a Class / Objects
  • 12. <?php $chuck = array("fullname" => "Chuck Severance", 'room' => '4429NQ'); $colleen = array("familyname" => "van Lent", 'givenname' => 'Colleen', 'room' => '3439NQ'); function get_person_name($person) { if ( isset($person['fullname']) ) return $person['fullname']; if ( isset($person['familyname']) && isset($person['givenname']) ) { return $person['givenname'] . ' ' . $person['familyname'] ; } return false; } print get_person_name($chuck) . "n"; print get_person_name($colleen) . "n"; Chuck Severance Colleen van Lent nonobj.php
  • 13. <?php class Person { public $fullname = false; public $givenname = false; public $familyname = false; public $room = false; function get_name() { if ( $this->fullname !== false ) return $this->fullname; if ( $this->familyname !== false && $this->givenname !== false ) { return $this->givenname . ' ' . $this->familyname; } return false; } } $chuck = new Person(); $chuck->fullname = "Chuck Severance"; $chuck->room = "4429NQ"; $colleen = new Person(); $colleen->familyname = 'van Lent'; $colleen->givenname = 'Colleen'; $colleen->room = '3439NQ'; print $chuck->get_name() . "n"; print $colleen->get_name() . "n"; Chuck Severance Colleen van Lent withobj.php
  • 15. Two New Operators • Access “static item” in a class echo DateTime::RFC822."n"; • Access item in an object echo $z->format('Y-m-d')."n";
  • 17. $x = new DateTime(); $y = new DateTime('now'); $z = new DateTime('2012-01-31');
  • 18. $x = new DateTime('1999-04-31'); $oops = DateTime::getLastErrors(); print_r($oops); Array ( [warning_count] => 1 [warnings] => Array ( [11] => The parsed date was invalid ) [error_count] => 0 [errors] => Array ( ) )
  • 19. $z = new DateTime('2012-01-31'); echo $z->format('Y-m-d')."n"; 2012-01-31
  • 22. Object Life Cycle • Objects are created, used and discarded. • We have special blocks of code (methods) that get called - At the moment of creation (constructor) - At the moment of destruction (destructor) • Constructors are used a lot. • Destructors are seldom used.
  • 23. Constructor The primary purpose of the constructor is to set up some instance variables to have the proper initial values when the object is created.
  • 24. class PartyAnimal { function __construct() { echo("Constructedn"); } function something() { echo("Somethingn"); } function __destruct() { echo("Destructedn"); } } echo("--Onen"); $x = new PartyAnimal(); echo("--Twon"); $y = new PartyAnimal(); echo("--Threen"); $x->something(); echo("--The End?n"); --One Constructed --Two Constructed --Three Something --The End? Destructed Destructed party.php
  • 25. Many Instances • We can create lots of objects - the class is the template for the object. • We can store each distinct object in its own variable. • We call this having multiple instances of the same class. • Each instance has its own copy of the instance variables.
  • 26. class Hello { protected $lang; // Only accessible in the class function __construct($lang) { $this->lang = $lang; } function greet() { if ( $this->lang == 'fr' ) return 'Bonjour'; if ( $this->lang == 'es' ) return 'Hola'; return 'Hello'; } } $hi = new Hello('es'); echo $hi->greet()."n"; Hola hello.php
  • 27. Definitions • Class - a template - Dog • Method or Message - A defined capability of a class - bark() • Object or Instance - A particular instance of a class - Lassie • Constructor - A method which is called when the instance / object is created
  • 29. Inheritance • When we make a new class we can reuse an existing class and inherit all the capabilities of an existing class and then add our own little bit to make our new class • Another form of store and reuse • Write once - reuse many times • The new class (child) has all the capabilities of the old class (parent) - and then some more
  • 30. Terminology: Inheritance http://en.wikipedia.org/wiki/Object-oriented_programming “Subclasses” are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.
  • 31. class Hello { protected $lang; function __construct($lang) { ... } function greet() { ... } } class Social extends Hello { function bye() { if ( $this->lang == 'fr' ) return 'Au revoir'; if ( $this->lang == 'es' ) return 'Adios'; return 'goodbye'; } } $hi = new Social('es'); echo $hi->greet()."n"; echo $hi->bye()."n"; Hola Adios goodbye.php
  • 32. Definitions • Class - a template - Dog • Method or Message - A defined capability of a class - bark() • Object or Instance - A particular instance of a class - Lassie • Constructor - A method which is called when the instance / object is created • Inheritance - the ability to take a class and extend it to make a new class
  • 33. Visibility Class member variables also have scope. • Public – can be accessed outside the class, inside the class, and in derived classes • Protected – can be accessed inside the class, and in derived classes • Private – can only be accessed inside the class (i.e. private variables are not visible in derived classes) http://www.php.net/manual/en/language.oop5.visibility.php
  • 34. class MyClass { public $pub = 'Public'; protected $pro = 'Protected'; private $priv = 'Private'; function printHello() { echo $this->pub."n"; echo $this->pro."n"; echo $this->priv."n"; } } $obj = new MyClass(); echo $obj->pub."n"; // Works echo $obj->pro."n"; // Fatal Error echo $obj->priv."n"; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private Public Public Protected Private visibility.php
  • 35. class MyClass2 extends MyClass { function printHello() { echo $this->pub."n"; echo $this->pro."n"; echo $this->priv."n"; // Undefined } } echo("--- MyClass2 ---n"); $obj2 = new MyClass2(); echo $obj2->pub."n"; // Works $obj2->printHello(); // Shows Public, Protected, Undefined --- MyClass2 --- Public Public Protected (false)
  • 36. Building an Object from Scratch • Sometimes a developer will prefer to make an object with public key-value pairs rather than an array. • Use where appropriate…
  • 37. $player = new stdClass(); $player->name = "Chuck"; $player->score = 0; $player->score++; print_r($player); class Player { public $name = "Sally"; public $score = 0; } $p2 = new Player(); $p2->score++; print_r($p2); stdClass Object ( [name] => Chuck [score] => 1 ) Player Object ( [name] => Sally [score] => 1 ) scratch.php
  • 38. Summary • Object Oriented programming is a very structured approach to code reuse. • There is a trend away from global function names and toward OO. • We can group data and functionality together and create many independent instances of a class.
  • 39. Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) as part of www.wa4e.com and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Insert new Contributors and Translators here including names and dates Continue new Contributors and Translators here
  • 40. Additional Source Information • Snowman Cookie Cutter" by Didriks is licensed under CC BY https://www.flickr.com/photos/dinnerseries/23570475099 • Photo from the television program Lassie. Lassie watches as Jeff (Tommy Rettig) works on his bike is Public Domain https://en.wikipedia.org/wiki/Lassie#/media/File:Lassie_and_Tommy_Rettig_1956.JPG

Editor's Notes

  1. Note from Chuck. Please retain and maintain this page as you remix and republish these materials. Please add any of your own improvements or contributions.