SlideShare une entreprise Scribd logo
1  sur  50
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?

Contenu connexe

Tendances (20)

PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
MVC in PHP
MVC in PHPMVC in PHP
MVC in PHP
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
Php array
Php arrayPhp array
Php array
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
PHP MVC
PHP MVCPHP MVC
PHP MVC
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
SQL
SQLSQL
SQL
 

En vedette

Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP ArraysAhmed Swilam
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database ProgrammingAhmed Swilam
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionAhmed Swilam
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHPAhmed Swilam
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingAhmed Swilam
 
PHP MVC Tutorial 2
PHP MVC Tutorial 2PHP MVC Tutorial 2
PHP MVC Tutorial 2Yang Bruce
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPRick Ogden
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
Why to choose laravel framework
Why to choose laravel frameworkWhy to choose laravel framework
Why to choose laravel frameworkBo-Yi Wu
 
How to choose web framework
How to choose web frameworkHow to choose web framework
How to choose web frameworkBo-Yi Wu
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP SecurityZendCon
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterSachin G Kulkarni
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 

En vedette (20)

Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
PHP MVC Tutorial 2
PHP MVC Tutorial 2PHP MVC Tutorial 2
PHP MVC Tutorial 2
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Why to choose laravel framework
Why to choose laravel frameworkWhy to choose laravel framework
Why to choose laravel framework
 
How to choose web framework
How to choose web frameworkHow to choose web framework
How to choose web framework
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP Security
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
PHP & MVC
PHP & MVCPHP & MVC
PHP & MVC
 

Similaire à Class 7 - PHP Object Oriented Programming

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 2017Alena 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 #pnwphpAlena Holligan
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
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 PHPAlena Holligan
 
Obect-Oriented Collaboration
Obect-Oriented CollaborationObect-Oriented Collaboration
Obect-Oriented CollaborationAlena Holligan
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Alena Holligan
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Alena Holligan
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHPwahidullah mudaser
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptxrani marri
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Getachew Ganfur
 

Similaire à Class 7 - PHP Object Oriented Programming (20)

Only oop
Only oopOnly oop
Only oop
 
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
OOP in PHPOOP in PHP
OOP in 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
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
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
 
Obect-Oriented Collaboration
Obect-Oriented CollaborationObect-Oriented Collaboration
Obect-Oriented Collaboration
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
Oops
OopsOops
Oops
 
Lab 4 (1).pdf
Lab 4 (1).pdfLab 4 (1).pdf
Lab 4 (1).pdf
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 

Dernier

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Dernier (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

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)