SlideShare a Scribd company logo
iFour ConsultancyOOP with PHP
web Engineering ||
winter 2017
wahidullah Mudaser
assignment.cs2017@gmail.com
 Lecture 09
 OOP in PHP
 Classes and objects
 Methods and properties
 Scope
 Inheritance
 Static methods and properties
 Constants
 Abstraction
 interfaces
OUTLINE
 The idea of Object Oriented Programming is to move the architecture of an
application closer to real world
 Classes are types of entities
 Objects are single units of a given class
 Example – Dog is a class, your dog Lassie is an object of class Dog
 Classes have methods and properties
 Classes and objects help to create well-structured application
Classes and objects
 Declaring of a class in PHP can be done anywhere in the code.
 Two special methods: constructor and destructor
 Executed when creating or destroying new object of this class
 Used to initialize or cleanup properties and etc.
Classes in PHP
class Dog {
… // declare methods and properties
}
Classes in PHP
 Class definition begins with the class keyword, followed by its name and
methods and properties list
 Objects of class (instances) are created with the keyword new
class A {
function foo () {
echo "foo here!";
}
}
$myFirstObject = new A();
$myFirstObject->foo(); // prints out "foo here!";
class name Method name and body
Create new object of class
A
Execute method of this
object
Constructors
 Each class can have only one constructor
 All parameters of the creating of the object are passed to the constructor
class A {
function __construct ($bar) {
echo $bar;
}
function foo () {
echo "foo here!";
}
}
$myFirstObject = new A('test');
// print 'test'
Properties
 Class can have unlimited number of properties
 The $this variable points to the current object – called execution
context
class A {
var $bar;
function __construct ($bar) {
$this->bar = $bar;
}
function myPrint () {
echo $this->bar;
}
}
$myFirstObject = new A('test');
$myFirstObject->myPrint();
More Properties
 Class can specify default value for a property
 Properties can be accessed from the outside world
class A {
var $bar = 'default value';
…
class A {
var $bar = 'default value';
…
}
$obj = new A;
echo $obj->bar;
$this
 Example of what $this is
 Can be used to access methods too
class A {
var $bar;
function __construct ($bar) {
$this->bar = $bar;
}
function myPrint () {
echo $this->bar;
}
}
$myFirstObject = new A('test');
$myFirstObject->myPrint(); // prints 'test'
$anotherObject = new A('foo');
$anotherObject ->myPrint(); // prints 'foo';
Destructors
 Each class can have only one destructor
 Must be public
 Destructors are automatically called when script is shutting down
class A {
function __construct ($name) {
$this->fp = fopen ($name, 'r');
}
function __destruct () {
fclose($this->fp);
}
}
$myFirstObject = new A('test');
Scope
 Each method and property has a scope
 It defines who can access it
 Three levels – public, protected, private
 Private can be access only by the object itself
 Protected can be accessed by descendant classes (see inheritance)
 Public can be accessed from the outside world
 Level is added before function keyword or instead of var
 var is old style (PHP 4) equivalent to public
 Constructors always need to be public
Scope Example
class A {
private $bar;
public function __construct ($bar) {
$this->bar = $bar;
}
public function myPrint () {
echo $this->bar;
}
}
$myFirstObject = new A('test');
$myFirstObject->myPrint(); // prints 'test'
// this will not work:
echo $myFirstObject->bar;
The $bar variable is private so only the
object can access it
The myPrint method is public, so
everyone can call it
Inheritance
 A class can inherit (extend) another class
 It inherits all its methods and properties
class A {
public $bar = 'test';
public function example () {
…
}
}
class B extends A {
…
}
$obj = new B();
echo $obj->bar; //prints 'test'
//calls the A-class function
$obj->example();
Protected Scope
 Method or property, declared as protected can be accessed in classes
that inherit it, but cannot be accessed from the outside world
class A {
protected $bar = 'test';
}
class B extends A {
public function foo () {
// this is allowed
$this->bar = 'I see it';
}
}
$obj = new B();
echo $obj->bar; //not allowed
Overriding
 When a class inherits another, it can declare methods that override parent class
methods
 Method names are the same
 Parameters may differ
class A {
public foo() { … }
}
class B extends A {
public foo() { … }
}
Overriding Example
class A {
public foo() {
echo 'called from A';
}
}
class B extends A {
public foo() {
echo 'called from B';
}
}
$obj1 = new A();
$obj2 = new B();
$obj1->foo(); // executes A's methods
$obj2->foo(); // executes B's methods
Accessing Parent Class
 As -> is used to access object's methods and properties, the :: (double colon) is
used to change scope
 Scope Resolution Operator
 parent:: can be used to access parent's class overridden methods
 Example: call parent's constructor in the child one
Accessing Parent Class
 Example of calling parent constructor
class A {
protected $variable;
public __construct() {
$this->variable = 'test';
}
}
class B extends A {
public __construct() {
parent::__construct();
echo $this->variable;
}
}
$obj1 = new B();
// prints 'test';
The static Keyword
 Defining method or property as 'static' makes them accessible without needing an
instantiation of a class
 Accessed with the double-colon (::) operator instead of the member (->) operator
 $this is not available in static methods
 Static properties and methods can also have scope defined – public, private or protected
The static Keyword
 Example of static method and property
 Class can access statics with the self keyword
 Outside world accesses statics with the class name
class A {
public static $myVariable;
public static function myPrint() {
echo self::$myVariable;
}
}
A::$myVariable = 'test';
A::myPrint();
Class Constants
 Constants in PHP usually are declared with the define function
 Constants can be defined in class
 Differ from normal variables – no need for $ symbol to declare and
access
 Declared with the const keyword
 Value must be supplied with the declaration
 Accessed with scope operator (::)
 Can be overridden by child classes
 Value must be constant expression, not a variable, class member, result
of operation or function call
Class Constants
 Example of a class constant
class A {
const myConstant = 'value';
public function showConstant() {
echo self::myConstant;
}
}
echo A::myConstant;
$obj = new A();
$obj->showConstant();
Abstraction
 Classes, defined as abstract, cannot have instances (cannot create object of
this class)
 Abstract class must have at least one abstract method
 Abstract methods do not have implementation (body) in the class
 Only signature
 The class must be inherited
 The child class must implement all abstract methods
 Cannot increase visibility
Abstraction Example
abstract class AbstractClass {
abstract protected function getValue();
abstract public function getValue2($prefix);
public function printOut () {
echo $this->getValue();
}
}
class Class1 extends AbstractClass {
protected function getValue (){
return "Class1";
}
public function getValue2($prefix) {
return $prefix."NAC1";
}
}
Abstraction Example (2)
// continue from previous slide
class Class2 extends AbstractClass {
protected function getValue (){
return "Class2";
}
public function getValue2($prefix) {
return $prefix."NAC2";
}
}
$class1 = new Class1();
$class1->printOut(); // "Class1";
echo $class1->getValue2('FOO'); // FOONAC1
$class2 = new Class2();
$class2->printOut(); // "Class2";
echo $class2->getValue2('FOO'); //FOONAC2
Interfaces
 Object interfaces allow you to specify what methods a child class must
implement
 Declared with the interface keyword
 Similar to abstract class
 Interface can have only public methods
 No method in interface can have implementation
 Interfaces are inherited with the implements keyword (instead of
extends)
 One class may implement multiple interfaces, if they do not have methods
with same names
Interface Example
interface iTemplate {
public function set ($name, $value);
public function getHTML($template);
}
class Template implements iTemplate {
private $vars = array();
public function set ($name, $value) {
$this->vars[$name] = $value;
}
public function getHTML($template) {
foreach($this->vars as $name=>$value) {
$template = str_replace(
'{'.$name.'}', $value, $template);
}
return $template;
}
}
Questions?
http://www.ifourtechnolab.com/ ASP.NET Software Development Companies India
Ad

Recommended

Introduction to php oop
Introduction to php oop
baabtra.com - No. 1 supplier of quality freshers
 
OOPS Basics With Example
OOPS Basics With Example
Thooyavan Venkatachalam
 
Php object orientation and classes
Php object orientation and classes
Kumar
 
Python unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
PHP OOP
PHP OOP
Oscar Merida
 
Advanced php
Advanced php
hamfu
 
OOP with Java - continued
OOP with Java - continued
RatnaJava
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Python programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
 
Advance OOP concepts in Python
Advance OOP concepts in Python
Sujith Kumar
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
Class object method constructors in java
Class object method constructors in java
Raja Sekhar
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
Mahmoud Alfarra
 
Core java oop
Core java oop
Parth Shah
 
C++ classes tutorials
C++ classes tutorials
FALLEE31188
 
Delegate
Delegate
rsvermacdac
 
38 object-concepts (1)
38 object-concepts (1)
Shambhavi Vats
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
38 object-concepts
38 object-concepts
raahulwasule
 
java tutorial 3
java tutorial 3
Tushar Desarda
 
java tutorial 2
java tutorial 2
Tushar Desarda
 
Lecture 7 arrays
Lecture 7 arrays
manish kumar
 
Java02
Java02
Vinod siragaon
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)
Infocampus Logics Pvt.Ltd.
 
Java unit2
Java unit2
Abhishek Khune
 
OOP in PHP
OOP in PHP
Henry Osborne
 
Only oop
Only oop
anitarooge
 

More Related Content

What's hot (20)

Python programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
 
Advance OOP concepts in Python
Advance OOP concepts in Python
Sujith Kumar
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
Class object method constructors in java
Class object method constructors in java
Raja Sekhar
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
Mahmoud Alfarra
 
Core java oop
Core java oop
Parth Shah
 
C++ classes tutorials
C++ classes tutorials
FALLEE31188
 
Delegate
Delegate
rsvermacdac
 
38 object-concepts (1)
38 object-concepts (1)
Shambhavi Vats
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
38 object-concepts
38 object-concepts
raahulwasule
 
java tutorial 3
java tutorial 3
Tushar Desarda
 
java tutorial 2
java tutorial 2
Tushar Desarda
 
Lecture 7 arrays
Lecture 7 arrays
manish kumar
 
Java02
Java02
Vinod siragaon
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)
Infocampus Logics Pvt.Ltd.
 
Java unit2
Java unit2
Abhishek Khune
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
 
Advance OOP concepts in Python
Advance OOP concepts in Python
Sujith Kumar
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
Class object method constructors in java
Class object method constructors in java
Raja Sekhar
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
Mahmoud Alfarra
 
C++ classes tutorials
C++ classes tutorials
FALLEE31188
 
38 object-concepts (1)
38 object-concepts (1)
Shambhavi Vats
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
38 object-concepts
38 object-concepts
raahulwasule
 

Similar to Object Oriented Programming in PHP (20)

OOP in PHP
OOP in PHP
Henry Osborne
 
Only oop
Only oop
anitarooge
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Object Oriented PHP5
Object Oriented PHP5
Jason Austin
 
Object oriented programming in php
Object oriented programming in php
Aashiq Kuchey
 
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
 
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
GammingWorld2
 
Introduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 
OOP in PHP
OOP in PHP
Tarek Mahmud Apu
 
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
 
Web 9 | OOP in PHP
Web 9 | OOP in PHP
Mohammad Imam Hossain
 
UNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
Bozhidar Boshnakov
 
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year cs
javed75
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Object Oriented PHP5
Object Oriented PHP5
Jason Austin
 
Object oriented programming in php
Object oriented programming in php
Aashiq Kuchey
 
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
 
Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
GammingWorld2
 
Introduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
Alena Holligan
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
Bozhidar Boshnakov
 
UNIT-IV WT web technology for 1st year cs
UNIT-IV WT web technology for 1st year cs
javed75
 
Ad

More from wahidullah mudaser (6)

AJAX-Asynchronous JavaScript and XML
AJAX-Asynchronous JavaScript and XML
wahidullah mudaser
 
XML - Extensive Markup Language
XML - Extensive Markup Language
wahidullah mudaser
 
PHP file handling
PHP file handling
wahidullah mudaser
 
PHP with MySQL
PHP with MySQL
wahidullah mudaser
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array.
wahidullah mudaser
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
Ad

Recently uploaded (20)

Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
The Growing Value and Application of FME & GenAI
The Growing Value and Application of FME & GenAI
Safe Software
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
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
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
The Growing Value and Application of FME & GenAI
The Growing Value and Application of FME & GenAI
Safe Software
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
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
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 

Object Oriented Programming in PHP

  • 1. iFour ConsultancyOOP with PHP web Engineering || winter 2017 wahidullah Mudaser [email protected]  Lecture 09  OOP in PHP
  • 2.  Classes and objects  Methods and properties  Scope  Inheritance  Static methods and properties  Constants  Abstraction  interfaces OUTLINE
  • 3.  The idea of Object Oriented Programming is to move the architecture of an application closer to real world  Classes are types of entities  Objects are single units of a given class  Example – Dog is a class, your dog Lassie is an object of class Dog  Classes have methods and properties  Classes and objects help to create well-structured application Classes and objects
  • 4.  Declaring of a class in PHP can be done anywhere in the code.  Two special methods: constructor and destructor  Executed when creating or destroying new object of this class  Used to initialize or cleanup properties and etc. Classes in PHP class Dog { … // declare methods and properties }
  • 5. Classes in PHP  Class definition begins with the class keyword, followed by its name and methods and properties list  Objects of class (instances) are created with the keyword new class A { function foo () { echo "foo here!"; } } $myFirstObject = new A(); $myFirstObject->foo(); // prints out "foo here!"; class name Method name and body Create new object of class A Execute method of this object
  • 6. Constructors  Each class can have only one constructor  All parameters of the creating of the object are passed to the constructor class A { function __construct ($bar) { echo $bar; } function foo () { echo "foo here!"; } } $myFirstObject = new A('test'); // print 'test'
  • 7. Properties  Class can have unlimited number of properties  The $this variable points to the current object – called execution context class A { var $bar; function __construct ($bar) { $this->bar = $bar; } function myPrint () { echo $this->bar; } } $myFirstObject = new A('test'); $myFirstObject->myPrint();
  • 8. More Properties  Class can specify default value for a property  Properties can be accessed from the outside world class A { var $bar = 'default value'; … class A { var $bar = 'default value'; … } $obj = new A; echo $obj->bar;
  • 9. $this  Example of what $this is  Can be used to access methods too class A { var $bar; function __construct ($bar) { $this->bar = $bar; } function myPrint () { echo $this->bar; } } $myFirstObject = new A('test'); $myFirstObject->myPrint(); // prints 'test' $anotherObject = new A('foo'); $anotherObject ->myPrint(); // prints 'foo';
  • 10. Destructors  Each class can have only one destructor  Must be public  Destructors are automatically called when script is shutting down class A { function __construct ($name) { $this->fp = fopen ($name, 'r'); } function __destruct () { fclose($this->fp); } } $myFirstObject = new A('test');
  • 11. Scope  Each method and property has a scope  It defines who can access it  Three levels – public, protected, private  Private can be access only by the object itself  Protected can be accessed by descendant classes (see inheritance)  Public can be accessed from the outside world  Level is added before function keyword or instead of var  var is old style (PHP 4) equivalent to public  Constructors always need to be public
  • 12. Scope Example class A { private $bar; public function __construct ($bar) { $this->bar = $bar; } public function myPrint () { echo $this->bar; } } $myFirstObject = new A('test'); $myFirstObject->myPrint(); // prints 'test' // this will not work: echo $myFirstObject->bar; The $bar variable is private so only the object can access it The myPrint method is public, so everyone can call it
  • 13. Inheritance  A class can inherit (extend) another class  It inherits all its methods and properties class A { public $bar = 'test'; public function example () { … } } class B extends A { … } $obj = new B(); echo $obj->bar; //prints 'test' //calls the A-class function $obj->example();
  • 14. Protected Scope  Method or property, declared as protected can be accessed in classes that inherit it, but cannot be accessed from the outside world class A { protected $bar = 'test'; } class B extends A { public function foo () { // this is allowed $this->bar = 'I see it'; } } $obj = new B(); echo $obj->bar; //not allowed
  • 15. Overriding  When a class inherits another, it can declare methods that override parent class methods  Method names are the same  Parameters may differ class A { public foo() { … } } class B extends A { public foo() { … } }
  • 16. Overriding Example class A { public foo() { echo 'called from A'; } } class B extends A { public foo() { echo 'called from B'; } } $obj1 = new A(); $obj2 = new B(); $obj1->foo(); // executes A's methods $obj2->foo(); // executes B's methods
  • 17. Accessing Parent Class  As -> is used to access object's methods and properties, the :: (double colon) is used to change scope  Scope Resolution Operator  parent:: can be used to access parent's class overridden methods  Example: call parent's constructor in the child one
  • 18. Accessing Parent Class  Example of calling parent constructor class A { protected $variable; public __construct() { $this->variable = 'test'; } } class B extends A { public __construct() { parent::__construct(); echo $this->variable; } } $obj1 = new B(); // prints 'test';
  • 19. The static Keyword  Defining method or property as 'static' makes them accessible without needing an instantiation of a class  Accessed with the double-colon (::) operator instead of the member (->) operator  $this is not available in static methods  Static properties and methods can also have scope defined – public, private or protected
  • 20. The static Keyword  Example of static method and property  Class can access statics with the self keyword  Outside world accesses statics with the class name class A { public static $myVariable; public static function myPrint() { echo self::$myVariable; } } A::$myVariable = 'test'; A::myPrint();
  • 21. Class Constants  Constants in PHP usually are declared with the define function  Constants can be defined in class  Differ from normal variables – no need for $ symbol to declare and access  Declared with the const keyword  Value must be supplied with the declaration  Accessed with scope operator (::)  Can be overridden by child classes  Value must be constant expression, not a variable, class member, result of operation or function call
  • 22. Class Constants  Example of a class constant class A { const myConstant = 'value'; public function showConstant() { echo self::myConstant; } } echo A::myConstant; $obj = new A(); $obj->showConstant();
  • 23. Abstraction  Classes, defined as abstract, cannot have instances (cannot create object of this class)  Abstract class must have at least one abstract method  Abstract methods do not have implementation (body) in the class  Only signature  The class must be inherited  The child class must implement all abstract methods  Cannot increase visibility
  • 24. Abstraction Example abstract class AbstractClass { abstract protected function getValue(); abstract public function getValue2($prefix); public function printOut () { echo $this->getValue(); } } class Class1 extends AbstractClass { protected function getValue (){ return "Class1"; } public function getValue2($prefix) { return $prefix."NAC1"; } }
  • 25. Abstraction Example (2) // continue from previous slide class Class2 extends AbstractClass { protected function getValue (){ return "Class2"; } public function getValue2($prefix) { return $prefix."NAC2"; } } $class1 = new Class1(); $class1->printOut(); // "Class1"; echo $class1->getValue2('FOO'); // FOONAC1 $class2 = new Class2(); $class2->printOut(); // "Class2"; echo $class2->getValue2('FOO'); //FOONAC2
  • 26. Interfaces  Object interfaces allow you to specify what methods a child class must implement  Declared with the interface keyword  Similar to abstract class  Interface can have only public methods  No method in interface can have implementation  Interfaces are inherited with the implements keyword (instead of extends)  One class may implement multiple interfaces, if they do not have methods with same names
  • 27. Interface Example interface iTemplate { public function set ($name, $value); public function getHTML($template); } class Template implements iTemplate { private $vars = array(); public function set ($name, $value) { $this->vars[$name] = $value; } public function getHTML($template) { foreach($this->vars as $name=>$value) { $template = str_replace( '{'.$name.'}', $value, $template); } return $template; } }