PHP Object Oriented
Programming
Outline
Previous programming trends
Brief History
OOP – What & Why
OOP - Fundamental Concepts
Terms – you should know
Class Diagrams
Notes on classes
OOP in practice
Class Example
Class Constructors
Class Destructors
Static Members
Class Constants
Inheritance
Class Exercise
Class Exercise Solution
Polymorphism
Garbage Collector
Object Messaging
Abstract Classes
Interfaces
Final Methods
Final Classes
Class Exception
Assignment
Previous programming trends
Procedural languages:
splits the program's source code into smaller
fragments – Pool programming.
Structured languages:
require more constraints in the flow and
organization of programs - Instead of using global
variables, it employs variables that are local to
every subroutine. ( Functions )
Brief History
"Objects" first appeared at MIT in the late 1950s and
early 1960s.
Simula (1967) is generally accepted as the first
language to have the primary features of an object-
oriented language.
OOP What & Why?
OOP stands for Object Oriented Programming.
It arranges codes and data structures into objects. They
simply are a collection of fields ( variables ) and functions.
OOP is considered one of the greatest inventions in computer
programming history.
OOP What & Why?
Why OOP ?
•Modularity
•Extensibility (sharing code - Polymorphism, Generics,
Interfaces)
•Reusability ( inheritance )
•Reliability (reduces large problems to smaller, more
manageable ones)
•Robustness (it is easy to map a real world problem to a
solution in OO code)
•Scalability (Multi-Tiered apps.)
•Maintainability
OOP - Fundamental Concepts
Abstraction - combining multiple smaller operations
into a single unit that can be referred to by name.
Encapsulation (information hiding) – separating
implementation from interfaces.
Inheritance - defining objects data types as extensions
and/or restrictions of other object data types.
Polymorphism - using the same name to invoke
different operations on objects of different data types.
Terms you should know
Class - a class is a construct that is used as a template to
create objects of that class. This blueprint describes the state
and behavior that the objects of the class all share.
Instance - One can have an instance of a class; the instance is
the actual object created at run-time.
Attributes/Properties - that represent its state
Operations/Methods - that represent its behaviour
Terms you should know
Below terms are known as “Access Modifiers”:
Public – The resource can be accessed from any scope
(default).
Private – The resource can only be accessed from
within the class where it is defined.
Protected - The resource can only be accessed from
within the class where it is defined and descendants.
Final – The resource is accessible from any scope, but
can not be overridden in descendants. It only applies to
methods and classes. Classes that are declared as final
cannot be extended.
Class Diagrams
Class Diagrams ( UML ) is used to describe structure
of classes.
Person
- Name: string
+ getName(): string
+ setName(): void
# _talk(): string
Class Attributes/Properties
Class Operations/Methods
Class Name
Private
Public
Protected
Data type
Class Diagrams
Person
- name: string
+ getName(): string
+ setName(): void
# _talk(): integer
class Person{
private $__name;
public function __construct(){}
public function setName($name){
$this->__name = $name;
}
public function getName(){
return $this->__name;
}
protected function _talk(){}
}
Notes on classes
• Class names are having the same rules as PHP
variables ( they start with character or underscore ,
etc).
• $this is a variable that refers to the current object
( see the previous example).
• Class objects are always passed by reference.
Class Example
class Point{
private $x;
private $y;
public function setPoint($x, $y){
$this->x = $x;
$this->y = $y;
}
public function show(){
echo “x = ” . $this->x . “, y = ”. $this-
>y;
}
}
$p = new Point();
$p->setPoint(2,5);
$p->show(); // x = 2, y = 5
Class Constructor
Constructors are executed in object creation time, they
look like this :
class Point{
function __construct(){
echo “Hello Classes”;
}
}
$p = new Point(); // Hello Classes
Class Destructors
Destructors are executed in object destruction time,
they look like this :
class Point{
function __destruct(){
echo “Good bye”;
}
}
$p = new Point(); // Good Bye
Static members
Declaring class properties or methods as static makes
them accessible without needing an object.
class Point{
public static $my_static = 'foo';
}
echo Point:: $my_static; // foo
Static members
Static functions :
class Point{
public static $my_static = 'foo';
public static function doSomthing(){
echo Point::$my_static;
// We can use self instead of Point
}
}
echo Point::doSomthing(); // foo
Class constants
Classes can contain constants within their definition.
Example:
class Point{
const PI = 3.14;
}
echo Point::PI;
Inheritance
Inheritance is the act of extending the functionality of
a class.
Inheritance(Cont.)
Example :
Class Employee extends Person { // Check slide #11
private $__salary = 0;
function __construct($name, $salary) {
$this->setName($name);
$this->setSalary($salary);
}
function setSalary($salary){
$this->__salary = $salary;
}
Inheritance(Cont.)
function getSalary(){
return $this->__salary;
}
}
$emp = new Employee(‘Mohammed’, 250);
echo ‘Name = ’, $emp->getName(), ‘, Salary = ’, $emp-
>getSalary();
Multiple Inheritance
Multiple inheritance can be applied using the following two
approaches(Multi-level inheritance by using interfaces)
Example :
class a {
function test() {
echo 'a::test called', PHP_EOL;
}
function func() {
echo 'a::func called', PHP_EOL;
}
}
Multiple Inheritance(Cont.)
class b extends a {
function test() {
echo 'b::test called', PHP_EOL;
}
}
class c extends b {
function test() {
parent::test();
}
}
Multiple Inheritance (Cont.)
class d extends c {
function test() {
# Note the call to b as it is not the direct parent.
b::test();
}
}
Multiple Inheritance (Cont.)
$a = new a();
$b = new b();
$c = new c();
$d = new d();
$a->test(); // Outputs "a::test called"
$b->test(); // Outputs "b::test called"
$b->func(); // Outputs "a::func called"
$c->test(); // Outputs "b::test called"
$d->test(); // Outputs "b::test called"
?>
Class Exercise
Create a PHP program that simulates a bank account. The
program should contain 2 classes, one is “Person” and other is
“BankAccount”.
Class Exercise Solution
class Person{
private $name = “”;
public function __construct($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
Class Exercise Solution
class BankAccount{
private $person = null;
private $amount = 0;
public function __construct($person){
$this->person = $person;
}
public function deposit( $num ){
$this->amount += $num;
}
public function withdraw( $num ){
$this->amount -= $num;
}
Class Exercise Solution
public function getAmount(){
return $this- >amount;
}
public function printStatement(){
echo ‘Name : ‘, $this- >person->getName() , “,
amount = ” , $this- >amount;
}
}
$p = new Person(“Mohamed”);
$b = new BankAccount($p);
$b->deposit(500);
$b->withdraw(100);
$b->printStatement(); // Name : Mohamed, amount = 400
Polymorphism
• Polymorphism describes a pattern in object oriented
programming in which classes have different
functionality while sharing a common interface.
Example :
class Person {
function whoAreYou(){
echo “I am Person”;
}
}
Polymorphism
class Employee extends Person {
function whoAreYou(){
echo ”I am an employee”;
}
}
$e = new Employee();
$e->whoAreYou(); // I am an employee
$p = new Person();
$p->whoAreYou(); // I am a person
Garbage Collector
Like Java, C#, PHP employs a garbage collector to
automatically clean up resources. Because the
programmer is not responsible for allocating and
freeing memory (as he is in a language like C++, for
example).
Object Messaging
Generalization AKA Inheritance
Person
Employee
Object Messaging (Cont.)
Association – Object Uses another object
FuelCar
Object Messaging (Cont.)
Composition – “is a” relationship, object can not
exist without another object.
FacultyUniversity
Object Messaging (Cont.)
Aggregation – “has a” relationship, object has
another object, but it is not dependent on the
other existence.
StudentFaculty
Abstract Classes
• It is not allowed to create an instance of a class
that has been defined as abstract.
• Any class that contains at least one abstract
method must also be abstract.
• Methods defined as abstract simply declare the
method's signature they cannot define the
implementation.
Abstract Classes(Cont.)
abstract class AbstractClass{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function myFoo($someParam);
// Common method
public function printOut() {
print $this->getValue() . '<br/>';
}
}
Abstract Classes(Cont.)
class MyClass extends AbstractClass{
protected function getValue() {
return "MyClass";
}
public function myFoo($x){
return $this->getValue(). '->my Foo('.$x. ') Called
<br/>';
}
}
$oMyObject = new MyClass;
$oMyObject ->printOut();
Interfaces
• Object interfaces allow you to create code which
specifies which methods a class must implement,
without having to define how these methods are
handled.
• All methods declared in an interface must be
public, this is the nature of an interface.
• A class cannot implement two interfaces that
share function names, since it would cause
ambiguity.
Interfaces(Cont.)
interface IActionable{
public function insert($data);
public function update($id);
public function save();
}
Interfaces(Cont.)
Class DataHandler implements IActionable{
public function insert($d){
echo $d, ‘ is inserted’;
}
public function update($y){/*Apply any logic in
here*/}
public function save(){
echo ‘Data is saved’;
}
}
Final Methods
• prevents child classes from overriding a method by
prefixing the definition with ‘final’.
Example
class ParentClass {
public function test() {
echo " ParentClass::test() calledn";
}
final public function moreTesting() {
echo "ParentClass ::moreTesting() calledn";
}
}
Final Methods(Cont.)
class ChildClass extends ParentClass {
public function moreTesting() {
echo "ChildClass::moreTesting() calledn";
}
}
// Results in Fatal error: Cannot override final method
ParentClass ::moreTesting()
Final Classes
• If the class itself is being defined final then it cannot be
extended.
Example
final class ParentClass {
public function test() {
echo "ParentClass::test() calledn";
}
final public function moreTesting() {
echo "ParentClass ::moreTesting() calledn";
}
}
Final Classes (Cont.)
class ChildClass extends ParentClass {
}
// Results in Fatal error: Class ChildClass may not inherit from
final class (ParentClass)
Class Exception
Exceptions are a way to handle errors. Exception = error. This is
implemented by creating a class that defines the type of error and this class
should extend the parent Exception class like the following :
class DivisionByZeroException extends Exception {
public function __construct($message, $code){
parent::__construct($message, $code);
}
}
$x = 0;
Try{
if( $x == 0 )
throw new DivisionByZeroException(‘division by zero’, 1);
else
echo 1/$x;
}catch(DivisionByZeroException $e){
echo $e->getMessage();
}
Assignment
We have 3 types of people; person, student and teacher.
Students and Teachers are Persons. A person has a name.
A student has class number and seat number. A Teacher
has a number of students whom he/she teaches.
Map these relationships into a PHP program that
contains all these 3 classes and all the functions that are
needed to ( set/get name, set/get seat number, set/get
class number, add a new student to a teacher group of
students)
What's Next?
• Database Programming.
Questions?

More Related Content

PPTX
Prototype model
PPT
Working with Databases and MySQL
PPTX
Operating Systems - File Management
PPTX
MS EXCEL PPT PRESENTATION
PPT
Operating System: Deadlock
PPTX
امن المعلومات المحاضرة الثانية
PPTX
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
PPTX
Introduction to laravel framework
Prototype model
Working with Databases and MySQL
Operating Systems - File Management
MS EXCEL PPT PRESENTATION
Operating System: Deadlock
امن المعلومات المحاضرة الثانية
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
Introduction to laravel framework

What's hot (20)

PPTX
Object oreinted php | OOPs
PPT
Oops concepts in php
PDF
Chap 4 PHP.pdf
PPT
Php with MYSQL Database
PDF
MVC in PHP
PDF
Php Tutorials for Beginners
PPT
PHP - Introduction to PHP AJAX
PPTX
MongoDB - Aggregation Pipeline
PPT
jQuery Ajax
PPT
Jsp/Servlet
PDF
Php tutorial(w3schools)
PDF
ES6 presentation
PDF
jQuery for beginners
PDF
Flask Introduction - Python Meetup
PPTX
Form Handling using PHP
PDF
Proxy design pattern (Class Ambassador)
PPTX
PPT
01 Php Introduction
PDF
Introduction into ES6 JavaScript.
PPTX
Express js
Object oreinted php | OOPs
Oops concepts in php
Chap 4 PHP.pdf
Php with MYSQL Database
MVC in PHP
Php Tutorials for Beginners
PHP - Introduction to PHP AJAX
MongoDB - Aggregation Pipeline
jQuery Ajax
Jsp/Servlet
Php tutorial(w3schools)
ES6 presentation
jQuery for beginners
Flask Introduction - Python Meetup
Form Handling using PHP
Proxy design pattern (Class Ambassador)
01 Php Introduction
Introduction into ES6 JavaScript.
Express js
Ad

Viewers also liked (20)

PPT
Class and Objects in PHP
PPT
Class 3 - PHP Functions
PPT
Class 4 - PHP Arrays
PPTX
Class 8 - Database Programming
PPT
Class 1 - World Wide Web Introduction
PPT
Class 2 - Introduction to PHP
PPT
Class 5 - PHP Strings
PPT
Class 6 - PHP Web Programming
PPT
Functions in php
PPT
Oops in PHP
PDF
PHP MVC Tutorial 2
KEY
PHPUnit testing to Zend_Test
ODP
Beginners Guide to Object Orientation in PHP
PDF
Intro To Mvc Development In Php
PPTX
Why to choose laravel framework
PPTX
How to choose web framework
PDF
Enterprise-Class PHP Security
PPTX
REST API Best Practices & Implementing in Codeigniter
ODP
CodeIgniter PHP MVC Framework
PDF
PHP & MVC
Class and Objects in PHP
Class 3 - PHP Functions
Class 4 - PHP Arrays
Class 8 - Database Programming
Class 1 - World Wide Web Introduction
Class 2 - Introduction to PHP
Class 5 - PHP Strings
Class 6 - PHP Web Programming
Functions in php
Oops in PHP
PHP MVC Tutorial 2
PHPUnit testing to Zend_Test
Beginners Guide to Object Orientation in PHP
Intro To Mvc Development In Php
Why to choose laravel framework
How to choose web framework
Enterprise-Class PHP Security
REST API Best Practices & Implementing in Codeigniter
CodeIgniter PHP MVC Framework
PHP & MVC
Ad

Similar to Class 7 - PHP Object Oriented Programming (20)

PPTX
Only oop
PDF
Demystifying Object-Oriented Programming - PHP UK Conference 2017
PDF
OOP in PHP
PDF
Take the Plunge with OOP from #pnwphp
PDF
Demystifying Object-Oriented Programming - ZendCon 2016
PPTX
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT III (8).pptx
PPTX
UNIT III (8).pptx
PPT
Object Oriented Programming Concept.Hello
PPTX
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
PDF
Demystifying Object-Oriented Programming - Lone Star PHP
PDF
Obect-Oriented Collaboration
PDF
Demystifying Object-Oriented Programming - PHP[tek] 2017
PDF
Demystifying oop
PDF
Demystifying Object-Oriented Programming #phpbnl18
PPT
Overview of Object Oriented Programming using C++
PDF
Object Oriented Programming in PHP
PPTX
Lecture-10_PHP-OOP.pptx
PDF
Lab 4 (1).pdf
Only oop
Demystifying Object-Oriented Programming - PHP UK Conference 2017
OOP in PHP
Take the Plunge with OOP from #pnwphp
Demystifying Object-Oriented Programming - ZendCon 2016
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT III (8).pptx
UNIT III (8).pptx
Object Oriented Programming Concept.Hello
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
Demystifying Object-Oriented Programming - Lone Star PHP
Obect-Oriented Collaboration
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying oop
Demystifying Object-Oriented Programming #phpbnl18
Overview of Object Oriented Programming using C++
Object Oriented Programming in PHP
Lecture-10_PHP-OOP.pptx
Lab 4 (1).pdf

Recently uploaded (20)

PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Flame analysis and combustion estimation using large language and vision assi...
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
CloudStack 4.21: First Look Webinar slides
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PPT
Module 1.ppt Iot fundamentals and Architecture
PPT
Geologic Time for studying geology for geologist
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
Two-dimensional Klein-Gordon and Sine-Gordon numerical solutions based on dee...
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Architecture types and enterprise applications.pdf
PDF
Zenith AI: Advanced Artificial Intelligence
DOCX
search engine optimization ppt fir known well about this
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
A comparative study of natural language inference in Swahili using monolingua...
Flame analysis and combustion estimation using large language and vision assi...
sbt 2.0: go big (Scala Days 2025 edition)
Consumable AI The What, Why & How for Small Teams.pdf
Custom Battery Pack Design Considerations for Performance and Safety
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
A review of recent deep learning applications in wood surface defect identifi...
Developing a website for English-speaking practice to English as a foreign la...
CloudStack 4.21: First Look Webinar slides
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Module 1.ppt Iot fundamentals and Architecture
Geologic Time for studying geology for geologist
A contest of sentiment analysis: k-nearest neighbor versus neural network
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
Two-dimensional Klein-Gordon and Sine-Gordon numerical solutions based on dee...
Getting started with AI Agents and Multi-Agent Systems
Architecture types and enterprise applications.pdf
Zenith AI: Advanced Artificial Intelligence
search engine optimization ppt fir known well about this

Class 7 - PHP Object Oriented Programming

  • 2. Outline Previous programming trends Brief History OOP – What & Why OOP - Fundamental Concepts Terms – you should know Class Diagrams Notes on classes OOP in practice Class Example Class Constructors Class Destructors Static Members Class Constants Inheritance Class Exercise Class Exercise Solution Polymorphism Garbage Collector Object Messaging Abstract Classes Interfaces Final Methods Final Classes Class Exception Assignment
  • 3. Previous programming trends Procedural languages: splits the program's source code into smaller fragments – Pool programming. Structured languages: require more constraints in the flow and organization of programs - Instead of using global variables, it employs variables that are local to every subroutine. ( Functions )
  • 4. Brief History "Objects" first appeared at MIT in the late 1950s and early 1960s. Simula (1967) is generally accepted as the first language to have the primary features of an object- oriented language.
  • 5. OOP What & Why? OOP stands for Object Oriented Programming. It arranges codes and data structures into objects. They simply are a collection of fields ( variables ) and functions. OOP is considered one of the greatest inventions in computer programming history.
  • 6. OOP What & Why? Why OOP ? •Modularity •Extensibility (sharing code - Polymorphism, Generics, Interfaces) •Reusability ( inheritance ) •Reliability (reduces large problems to smaller, more manageable ones) •Robustness (it is easy to map a real world problem to a solution in OO code) •Scalability (Multi-Tiered apps.) •Maintainability
  • 7. OOP - Fundamental Concepts Abstraction - combining multiple smaller operations into a single unit that can be referred to by name. Encapsulation (information hiding) – separating implementation from interfaces. Inheritance - defining objects data types as extensions and/or restrictions of other object data types. Polymorphism - using the same name to invoke different operations on objects of different data types.
  • 8. Terms you should know Class - a class is a construct that is used as a template to create objects of that class. This blueprint describes the state and behavior that the objects of the class all share. Instance - One can have an instance of a class; the instance is the actual object created at run-time. Attributes/Properties - that represent its state Operations/Methods - that represent its behaviour
  • 9. Terms you should know Below terms are known as “Access Modifiers”: Public – The resource can be accessed from any scope (default). Private – The resource can only be accessed from within the class where it is defined. Protected - The resource can only be accessed from within the class where it is defined and descendants. Final – The resource is accessible from any scope, but can not be overridden in descendants. It only applies to methods and classes. Classes that are declared as final cannot be extended.
  • 10. Class Diagrams Class Diagrams ( UML ) is used to describe structure of classes. Person - Name: string + getName(): string + setName(): void # _talk(): string Class Attributes/Properties Class Operations/Methods Class Name Private Public Protected Data type
  • 11. Class Diagrams Person - name: string + getName(): string + setName(): void # _talk(): integer class Person{ private $__name; public function __construct(){} public function setName($name){ $this->__name = $name; } public function getName(){ return $this->__name; } protected function _talk(){} }
  • 12. Notes on classes • Class names are having the same rules as PHP variables ( they start with character or underscore , etc). • $this is a variable that refers to the current object ( see the previous example). • Class objects are always passed by reference.
  • 13. Class Example class Point{ private $x; private $y; public function setPoint($x, $y){ $this->x = $x; $this->y = $y; } public function show(){ echo “x = ” . $this->x . “, y = ”. $this- >y; } } $p = new Point(); $p->setPoint(2,5); $p->show(); // x = 2, y = 5
  • 14. Class Constructor Constructors are executed in object creation time, they look like this : class Point{ function __construct(){ echo “Hello Classes”; } } $p = new Point(); // Hello Classes
  • 15. Class Destructors Destructors are executed in object destruction time, they look like this : class Point{ function __destruct(){ echo “Good bye”; } } $p = new Point(); // Good Bye
  • 16. Static members Declaring class properties or methods as static makes them accessible without needing an object. class Point{ public static $my_static = 'foo'; } echo Point:: $my_static; // foo
  • 17. Static members Static functions : class Point{ public static $my_static = 'foo'; public static function doSomthing(){ echo Point::$my_static; // We can use self instead of Point } } echo Point::doSomthing(); // foo
  • 18. Class constants Classes can contain constants within their definition. Example: class Point{ const PI = 3.14; } echo Point::PI;
  • 19. Inheritance Inheritance is the act of extending the functionality of a class.
  • 20. Inheritance(Cont.) Example : Class Employee extends Person { // Check slide #11 private $__salary = 0; function __construct($name, $salary) { $this->setName($name); $this->setSalary($salary); } function setSalary($salary){ $this->__salary = $salary; }
  • 21. Inheritance(Cont.) function getSalary(){ return $this->__salary; } } $emp = new Employee(‘Mohammed’, 250); echo ‘Name = ’, $emp->getName(), ‘, Salary = ’, $emp- >getSalary();
  • 22. Multiple Inheritance Multiple inheritance can be applied using the following two approaches(Multi-level inheritance by using interfaces) Example : class a { function test() { echo 'a::test called', PHP_EOL; } function func() { echo 'a::func called', PHP_EOL; } }
  • 23. Multiple Inheritance(Cont.) class b extends a { function test() { echo 'b::test called', PHP_EOL; } } class c extends b { function test() { parent::test(); } }
  • 24. Multiple Inheritance (Cont.) class d extends c { function test() { # Note the call to b as it is not the direct parent. b::test(); } }
  • 25. Multiple Inheritance (Cont.) $a = new a(); $b = new b(); $c = new c(); $d = new d(); $a->test(); // Outputs "a::test called" $b->test(); // Outputs "b::test called" $b->func(); // Outputs "a::func called" $c->test(); // Outputs "b::test called" $d->test(); // Outputs "b::test called" ?>
  • 26. Class Exercise Create a PHP program that simulates a bank account. The program should contain 2 classes, one is “Person” and other is “BankAccount”.
  • 27. Class Exercise Solution class Person{ private $name = “”; public function __construct($name){ $this->name = $name; } public function getName(){ return $this->name; } }
  • 28. Class Exercise Solution class BankAccount{ private $person = null; private $amount = 0; public function __construct($person){ $this->person = $person; } public function deposit( $num ){ $this->amount += $num; } public function withdraw( $num ){ $this->amount -= $num; }
  • 29. Class Exercise Solution public function getAmount(){ return $this- >amount; } public function printStatement(){ echo ‘Name : ‘, $this- >person->getName() , “, amount = ” , $this- >amount; } } $p = new Person(“Mohamed”); $b = new BankAccount($p); $b->deposit(500); $b->withdraw(100); $b->printStatement(); // Name : Mohamed, amount = 400
  • 30. Polymorphism • Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface. Example : class Person { function whoAreYou(){ echo “I am Person”; } }
  • 31. Polymorphism class Employee extends Person { function whoAreYou(){ echo ”I am an employee”; } } $e = new Employee(); $e->whoAreYou(); // I am an employee $p = new Person(); $p->whoAreYou(); // I am a person
  • 32. Garbage Collector Like Java, C#, PHP employs a garbage collector to automatically clean up resources. Because the programmer is not responsible for allocating and freeing memory (as he is in a language like C++, for example).
  • 33. Object Messaging Generalization AKA Inheritance Person Employee
  • 34. Object Messaging (Cont.) Association – Object Uses another object FuelCar
  • 35. Object Messaging (Cont.) Composition – “is a” relationship, object can not exist without another object. FacultyUniversity
  • 36. Object Messaging (Cont.) Aggregation – “has a” relationship, object has another object, but it is not dependent on the other existence. StudentFaculty
  • 37. Abstract Classes • It is not allowed to create an instance of a class that has been defined as abstract. • Any class that contains at least one abstract method must also be abstract. • Methods defined as abstract simply declare the method's signature they cannot define the implementation.
  • 38. Abstract Classes(Cont.) abstract class AbstractClass{ // Force Extending class to define this method abstract protected function getValue(); abstract protected function myFoo($someParam); // Common method public function printOut() { print $this->getValue() . '<br/>'; } }
  • 39. Abstract Classes(Cont.) class MyClass extends AbstractClass{ protected function getValue() { return "MyClass"; } public function myFoo($x){ return $this->getValue(). '->my Foo('.$x. ') Called <br/>'; } } $oMyObject = new MyClass; $oMyObject ->printOut();
  • 40. Interfaces • Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. • All methods declared in an interface must be public, this is the nature of an interface. • A class cannot implement two interfaces that share function names, since it would cause ambiguity.
  • 41. Interfaces(Cont.) interface IActionable{ public function insert($data); public function update($id); public function save(); }
  • 42. Interfaces(Cont.) Class DataHandler implements IActionable{ public function insert($d){ echo $d, ‘ is inserted’; } public function update($y){/*Apply any logic in here*/} public function save(){ echo ‘Data is saved’; } }
  • 43. Final Methods • prevents child classes from overriding a method by prefixing the definition with ‘final’. Example class ParentClass { public function test() { echo " ParentClass::test() calledn"; } final public function moreTesting() { echo "ParentClass ::moreTesting() calledn"; } }
  • 44. Final Methods(Cont.) class ChildClass extends ParentClass { public function moreTesting() { echo "ChildClass::moreTesting() calledn"; } } // Results in Fatal error: Cannot override final method ParentClass ::moreTesting()
  • 45. Final Classes • If the class itself is being defined final then it cannot be extended. Example final class ParentClass { public function test() { echo "ParentClass::test() calledn"; } final public function moreTesting() { echo "ParentClass ::moreTesting() calledn"; } }
  • 46. Final Classes (Cont.) class ChildClass extends ParentClass { } // Results in Fatal error: Class ChildClass may not inherit from final class (ParentClass)
  • 47. Class Exception Exceptions are a way to handle errors. Exception = error. This is implemented by creating a class that defines the type of error and this class should extend the parent Exception class like the following : class DivisionByZeroException extends Exception { public function __construct($message, $code){ parent::__construct($message, $code); } } $x = 0; Try{ if( $x == 0 ) throw new DivisionByZeroException(‘division by zero’, 1); else echo 1/$x; }catch(DivisionByZeroException $e){ echo $e->getMessage(); }
  • 48. Assignment We have 3 types of people; person, student and teacher. Students and Teachers are Persons. A person has a name. A student has class number and seat number. A Teacher has a number of students whom he/she teaches. Map these relationships into a PHP program that contains all these 3 classes and all the functions that are needed to ( set/get name, set/get seat number, set/get class number, add a new student to a teacher group of students)