Class 7 - PHP Object Oriented Programming

Preview:

Citation preview

PHP Object Oriented Programming

OutlinePrevious programming trendsBrief HistoryOOP – What & WhyOOP - Fundamental ConceptsTerms – you should knowClass DiagramsNotes on classesOOP in practiceClass ExampleClass ConstructorsClass DestructorsStatic MembersClass Constants

InheritanceClass ExerciseClass Exercise SolutionPolymorphismGarbage CollectorObject MessagingAbstract ClassesInterfacesFinal MethodsFinal ClassesClass ExceptionAssignment

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 knowClass - 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 stateOperations/Methods - that represent its behaviour

Terms you should knowBelow 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 DiagramsClass 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 ConstructorConstructors are executed in object creation time, they look like this :

class Point{ function __construct(){

echo “Hello Classes”; }

}$p = new Point(); // Hello Classes

Class DestructorsDestructors are executed in object destruction time, they look like this : class Point{ function __destruct(){

echo “Good bye”; }

}$p = new Point(); // Good Bye

Static membersDeclaring 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 membersStatic 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 constantsClasses can contain constants within their definition.

Example:

class Point{ const PI = 3.14;

}

echo Point::PI;

InheritanceInheritance 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 InheritanceMultiple 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 ExerciseCreate a PHP program that simulates a bank account. The program should contain 2 classes, one is “Person” and other is “BankAccount”.

Class Exercise Solutionclass Person{

private $name = “”;

public function __construct($name){ $this->name = $name;

}

public function getName(){ return $this->name;

}}

Class Exercise Solutionclass 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 Solutionpublic 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”; }}

Polymorphismclass 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 CollectorLike 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 MessagingGeneralization 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();echo $oMyObject ->myFoo(10);

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’. Exampleclass ParentClass { public function test() { echo " ParentClass::test() called\n"; } final public function moreTesting() { echo "ParentClass ::moreTesting() called\n"; }}

Final Methods(Cont.)class ChildClass extends ParentClass { public function moreTesting() { echo "ChildClass::moreTesting() called\n"; }}// 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. Examplefinal class ParentClass { public function test() { echo "ParentClass::test() called\n"; } final public function moreTesting() { echo "ParentClass ::moreTesting() called\n"; }}

Final Classes (Cont.)class ChildClass extends ParentClass {}// Results in Fatal error: Class ChildClass may not inherit from final class (ParentClass)

Class ExceptionExceptions 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);

elseecho 1/$x;

}catch(DivisionByZeroException $e){echo $e->getMessage();

}

AssignmentWe 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?

Recommended