class 7 - php object oriented programming

50
PHP Object Oriented Programming

Upload: ahmed-swilam

Post on 15-Apr-2017

688 views

Category:

Technology


5 download

TRANSCRIPT

Page 1: Class 7 - PHP Object Oriented Programming

PHP Object Oriented Programming

Page 2: Class 7 - 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

Page 3: Class 7 - PHP Object Oriented Programming

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 )

Page 4: Class 7 - PHP Object Oriented Programming

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.

Page 5: Class 7 - PHP Object Oriented Programming

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.

Page 6: Class 7 - PHP Object Oriented Programming

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

Page 7: Class 7 - PHP Object Oriented Programming

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.

Page 8: Class 7 - PHP Object Oriented Programming

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

Page 9: Class 7 - PHP Object Oriented Programming

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.

Page 10: Class 7 - PHP Object Oriented Programming

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

Page 11: Class 7 - PHP Object Oriented Programming

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(){}}

Page 12: Class 7 - PHP Object Oriented Programming

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.

Page 13: Class 7 - PHP Object Oriented Programming

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

Page 14: Class 7 - PHP Object Oriented Programming

Class ConstructorConstructors are executed in object creation time, they look like this :

class Point{ function __construct(){

echo “Hello Classes”; }

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

Page 15: Class 7 - PHP Object Oriented Programming

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

echo “Good bye”; }

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

Page 16: Class 7 - PHP Object Oriented Programming

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

Page 17: Class 7 - PHP Object Oriented Programming

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

Page 18: Class 7 - PHP Object Oriented Programming

Class constantsClasses can contain constants within their definition.

Example:

class Point{ const PI = 3.14;

}

echo Point::PI;

Page 19: Class 7 - PHP Object Oriented Programming

InheritanceInheritance is the act of extending the functionality of a class.

Page 20: Class 7 - PHP Object Oriented Programming

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; }

Page 21: Class 7 - PHP Object Oriented Programming

Inheritance(Cont.) function getSalary(){

return $this->__salary; }

}$emp = new Employee(‘Mohammed’, 250);echo ‘Name = ’, $emp->getName(), ‘, Salary = ’, $emp->getSalary();

Page 22: Class 7 - PHP Object Oriented Programming

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; }

}

Page 23: Class 7 - PHP Object Oriented Programming

Multiple Inheritance(Cont.)class b extends a {

function test() { echo 'b::test called', PHP_EOL; }}class c extends b {

function test() { parent::test(); }}

Page 24: Class 7 - PHP Object Oriented Programming

Multiple Inheritance (Cont.)class d extends c {

function test() { # Note the call to b as it is not the direct parent. b::test(); }}

Page 25: Class 7 - PHP Object Oriented Programming

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

Page 26: Class 7 - PHP Object Oriented Programming

Class ExerciseCreate a PHP program that simulates a bank account. The program should contain 2 classes, one is “Person” and other is “BankAccount”.

Page 27: Class 7 - PHP Object Oriented Programming

Class Exercise Solutionclass Person{

private $name = “”;

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

}

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

}}

Page 28: Class 7 - PHP Object Oriented Programming

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; }

Page 29: Class 7 - PHP Object Oriented Programming

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

Page 30: Class 7 - PHP Object Oriented Programming

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”; }}

Page 31: Class 7 - PHP Object Oriented Programming

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

Page 32: Class 7 - PHP Object Oriented Programming

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).

Page 33: Class 7 - PHP Object Oriented Programming

Object MessagingGeneralization AKA Inheritance

Person

Employee

Page 34: Class 7 - PHP Object Oriented Programming

Object Messaging (Cont.)Association – Object Uses another object

FuelCar

Page 35: Class 7 - PHP Object Oriented Programming

Object Messaging (Cont.)Composition – “is a” relationship, object can not

exist without another object.

FacultyUniversity

Page 36: Class 7 - PHP Object Oriented Programming

Object Messaging (Cont.)Aggregation – “has a” relationship, object has

another object, but it is not dependent on the other existence.

StudentFaculty

Page 37: Class 7 - PHP Object Oriented Programming

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.

Page 38: Class 7 - PHP Object Oriented Programming

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/>'; }}

Page 39: Class 7 - PHP Object Oriented Programming

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

Page 40: Class 7 - PHP Object Oriented Programming

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.

Page 41: Class 7 - PHP Object Oriented Programming

Interfaces(Cont.)interface IActionable{ public function insert($data); public function update($id); public function save();}

Page 42: Class 7 - PHP Object Oriented Programming

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’; }}

Page 43: Class 7 - PHP Object Oriented Programming

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"; }}

Page 44: Class 7 - PHP Object Oriented Programming

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()

Page 45: Class 7 - PHP Object Oriented Programming

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"; }}

Page 46: Class 7 - PHP Object Oriented Programming

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

Page 47: Class 7 - PHP Object Oriented Programming

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();

}

Page 48: Class 7 - PHP Object Oriented Programming

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)

Page 49: Class 7 - PHP Object Oriented Programming

What's Next?• Database Programming.

Page 50: Class 7 - PHP Object Oriented Programming

Questions?