This document provides an overview of object-oriented programming (OOP) concepts in PHP. It discusses previous programming trends like procedural and structured languages. It then covers key OOP concepts like classes, objects, inheritance, polymorphism, and abstraction. Specific PHP OOP features are explained like class diagrams, access modifiers, constructors, destructors, static members, and class constants. Examples are provided to demonstrate classes, inheritance, polymorphism, abstract classes, interfaces, and exceptions. The document concludes with an assignment to model person, student, and teacher relationships using PHP classes.
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;
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();
}
}
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).
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.
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)