introduction to oop with php

33
OOP with PHP OOP with PHP Michael Peacock Michael Peacock

Upload: michael-peacock

Post on 27-May-2015

1.393 views

Category:

Technology


43 download

TRANSCRIPT

Page 1: Introduction to OOP with PHP

OOP with PHPOOP with PHPMichael PeacockMichael Peacock

Page 2: Introduction to OOP with PHP

Whats in storeWhats in store

OOP IntroductionOOP Introduction

Classes and ObjectsClasses and Objects

EncapsulationEncapsulation

PolymorphismPolymorphism

InheritanceInheritance

Page 3: Introduction to OOP with PHP

OOP introductionOOP introduction

Page 4: Introduction to OOP with PHP

Introduction to OOPIntroduction to OOP

Concepts are represented as objectsConcepts are represented as objects

Objects have Objects have propertiesproperties which contain which contain information about the objectinformation about the object

Functions associated with objects are called Functions associated with objects are called methodsmethods

Page 5: Introduction to OOP with PHP

Classes and objectsClasses and objects

Page 6: Introduction to OOP with PHP

Classes and ObjectsClasses and Objects

A class is a definition of an object. It is a file A class is a definition of an object. It is a file containing:containing:

The namespace of the classThe namespace of the class

The name of the classThe name of the class

A list of the properties of the classA list of the properties of the class

Implementations of any methodsImplementations of any methods

A class becomes an object when it is A class becomes an object when it is instantiated with the instantiated with the newnew keyword keyword

Page 7: Introduction to OOP with PHP

Defining a classDefining a class

<?phpclass MyClass {

// implementation of the class goes in here

}

Page 8: Introduction to OOP with PHP

VisibilityVisibility

Public Public refers to methods and properties which can be refers to methods and properties which can be accessed or called from both within the object itself accessed or called from both within the object itself and outside of the object (e.g. other files and objects)and outside of the object (e.g. other files and objects)

Private Private refers to methods and properties which can refers to methods and properties which can only be accessed or called from within the object only be accessed or called from within the object itselfitself

ProtectedProtected refers to methods and properties which refers to methods and properties which can be accessed or called from within the object itself can be accessed or called from within the object itself andand objects which extend from the object (child objects which extend from the object (child objects)objects)

Page 9: Introduction to OOP with PHP

Methods and PropertiesMethods and Properties

<?phpclass MyClass {

private $someProperty = 'a default value';private $anotherPropert;

public function myMethod(){

echo "This is my method being run";}

}

Page 10: Introduction to OOP with PHP

Magic MethodsMagic Methods

These are methods which are called These are methods which are called automatically when certain actions are automatically when certain actions are

undertaken, though they can be undertaken, though they can be manually called too. manually called too.

Typically prefixed with two underscoresTypically prefixed with two underscores

Page 11: Introduction to OOP with PHP

Magic methodsMagic methods

__construct __construct the constructor method; called on an object as the constructor method; called on an object as soon as it is instantiated. It can accept parameters.soon as it is instantiated. It can accept parameters.

__destruct__destruct the destructor method; called when an object the destructor method; called when an object stops being used/referenced or during shutdown sequencestops being used/referenced or during shutdown sequence

__toString__toString is called when you try to use an object as a string is called when you try to use an object as a string (e.g. echo $my_object) and returns the string representation (e.g. echo $my_object) and returns the string representation of the objectof the object

__clone__clone is called when you try and clone an object (e.g. is called when you try and clone an object (e.g. $new_object = clone $old_object) useful for dereferencing $new_object = clone $old_object) useful for dereferencing any unique IDs, etc.any unique IDs, etc.

Full list: Full list: http://php.net/manual/en/language.oop5.magic.phphttp://php.net/manual/en/language.oop5.magic.php

Page 12: Introduction to OOP with PHP

With a constructorWith a constructor<?phpclass MyClass {

private $someProperty = 'a default value';private $anotherPropert;

public function __construct(){

echo "this is called when you create the object";}

public function myMethod(){

echo "This is my method being run";}

}

Page 13: Introduction to OOP with PHP

Working with objectsWorking with objects

CreatingCreating$my_object = new SomeObject();$my_object = new SomeObject();

Accessing propertiesAccessing propertiesecho $my_object->someProperty; // must be echo $my_object->someProperty; // must be publicpublic

Calling methodsCalling methods$my_object->someMethods(); // must be public$my_object->someMethods(); // must be public

Page 14: Introduction to OOP with PHP

$this$thisWhen working within an object, you access When working within an object, you access properties and methods within the object using properties and methods within the object using the $this keyword. the $this keyword.

For example, consider a method which returns For example, consider a method which returns the total cost for an order. This needs to add the the total cost for an order. This needs to add the cost and the delivery cost. Both of these costs cost and the delivery cost. Both of these costs are calculated using other methodsare calculated using other methods

return $this->calculateCost() + $this-return $this->calculateCost() + $this->calculateDeliveryCost();>calculateDeliveryCost();

Page 15: Introduction to OOP with PHP

StaticStaticProperties can be accessed and Properties can be accessed and methods can be called from an methods can be called from an

uninstantiated class (i.e. not an object) uninstantiated class (i.e. not an object) if they are prefixed with the static if they are prefixed with the static

keyword. They are called and accessed keyword. They are called and accessed with the Scope Resolution Operator (::)with the Scope Resolution Operator (::)

class MyClass {public static function printHello(){print “hello”;}

}

MyClass::printHello();

Page 16: Introduction to OOP with PHP

Class constantsClass constants

Classes can also contain Classes can also contain constantsconstants; these are ; these are similar to properties except they cannot be similar to properties except they cannot be changed (unless you edit the php file of changed (unless you edit the php file of course!)course!)

const myConstant = “some value”;

Page 17: Introduction to OOP with PHP

Interfaces and Interfaces and ImplementsImplements

An An interfaceinterface defines non-private methods (as defines non-private methods (as well as the number of parameters they accept) well as the number of parameters they accept) that a class which that a class which implementsimplements the interface the interface must havemust have

If a class specifically If a class specifically implementsimplements an an interfaceinterface it it mustmust implement the methods implement the methods defined, if it does not PHP will raise errors.defined, if it does not PHP will raise errors.

Page 18: Introduction to OOP with PHP

Defining an interfaceDefining an interface

<?phpinterface MyInterface {

public function mustImplementThis();

public function mustImplementThisAsWell($with, $some, $parameters=null);

}

Page 19: Introduction to OOP with PHP

Creating a class which Creating a class which implements an interfaceimplements an interface

<?phpclass MyClass implements MyInterface {

public function mustImplementThis(){

// put some code here}

public function mustImplementThisAsWell($with, $some, $parameters=null){

// put some code here}

}

Page 20: Introduction to OOP with PHP

ExtendsExtends

One class can One class can extendextend another. When it does another. When it does this the class inherits properties, methods and this the class inherits properties, methods and constants from the constants from the parentparent class (the one it class (the one it extendsextends) - this is where visibility settings are ) - this is where visibility settings are essential.essential.

Public and protected properties and methods Public and protected properties and methods can be overridden in the child class; provided can be overridden in the child class; provided the method names and number of parameters the method names and number of parameters match.match.

Page 21: Introduction to OOP with PHP

Extends in actionExtends in action

<?phpclass MyChildClass extends MyParentClass {

// now we have a class which has the same properties// and methods as the MyParentClass

// we can add new ones here and override the parent ones// if we want to

}

Page 22: Introduction to OOP with PHP

Parent keywordParent keyword

If you have a method in a If you have a method in a childchild class from class from which you want to access properties or which you want to access properties or methods in the methods in the parentparent class, you use the class, you use the parentparent keyword with the scope resolution keyword with the scope resolution operator.operator.

<?phpclass Someclass extends Parentclass {

public function test(){

// this will call the someMethod method// in the Parentclass classecho parent::someMethod();

}

}

Page 23: Introduction to OOP with PHP

Abstract classAbstract class

An An abstractabstract class gives us the best of both class gives us the best of both worlds; we can define methods which need to be worlds; we can define methods which need to be implementedimplemented andand we can create methods and we can create methods and properties which can be properties which can be extendedextended by a by a childchild classclass

An abstract class is defined using the abstract An abstract class is defined using the abstract keywordkeyword

However...an abstract class cannot be However...an abstract class cannot be instantiated directly. Only a class which extends it instantiated directly. Only a class which extends it can be instantiated.can be instantiated.

Page 24: Introduction to OOP with PHP

Defining an abstract Defining an abstract classclass

<?phpabstract class MyAbstractClass {

protected $someProperty;

public function implementMe();public function implementMeToo();

protected function someMethod(){

echo 'a';}

public function __toString(){

return $this->someProperty;}

}

Page 25: Introduction to OOP with PHP

Using an abstract classUsing an abstract class<?phpclass MyClass extends AbstractClass {

protected $someProperty;

public function implementMe(){

// implementation}

public function implementMeToo(){

// implementation}

// we dont need to implement someMethod() or __toString// as the abstract class implements them// we can override them if we want to

}

Page 26: Introduction to OOP with PHP

EncapsulationEncapsulation

Page 27: Introduction to OOP with PHP

EncapsulationEncapsulationWith encapsulation the With encapsulation the internal representationinternal representation of an of an

object is hidden from view outside of the class. Often only object is hidden from view outside of the class. Often only the object itself is permitted to directly access and modify the object itself is permitted to directly access and modify

its properties.its properties.

This approach means we, the programmer, can have This approach means we, the programmer, can have greater control over how these properties are modified.greater control over how these properties are modified.

Imagine setting an email address property when a user Imagine setting an email address property when a user fills out a contact form. If the property is public, then the fills out a contact form. If the property is public, then the property could be any value. If we hide the property and property could be any value. If we hide the property and

use a setter method, we can put some business logic use a setter method, we can put some business logic between the user input and the property such as some between the user input and the property such as some

validation.validation.

Page 28: Introduction to OOP with PHP

PolymorphismPolymorphism

Page 29: Introduction to OOP with PHP
Page 30: Introduction to OOP with PHP

PolymorphismPolymorphism

Polymorphism allows an Polymorphism allows an object, variable or function object, variable or function have more than one form. have more than one form.

Page 31: Introduction to OOP with PHP

Why polymorphismWhy polymorphism

You have a class (Email) which represents an emailYou have a class (Email) which represents an email

You have a number of classes which can take an email You have a number of classes which can take an email object and send it using a specific technology (e.g. SMTP, object and send it using a specific technology (e.g. SMTP, sendmail, postmarkapp) lets use SmtpTransport as an sendmail, postmarkapp) lets use SmtpTransport as an exampleexample

When you need to send an email you have some code When you need to send an email you have some code (emailer code) which takes the email, takes the (emailer code) which takes the email, takes the SmtpTransport and links the two togetherSmtpTransport and links the two together

If you want to use your other class, PostmarkappTransport If you want to use your other class, PostmarkappTransport how does “email code” know how to work with how does “email code” know how to work with PostmarkappTransport...these are both different classesPostmarkappTransport...these are both different classes

Page 32: Introduction to OOP with PHP

Why polymorphism...Why polymorphism...

Answer: Interfaces and polymorphismAnswer: Interfaces and polymorphism

We have a TransportInterface which defines the public methods we We have a TransportInterface which defines the public methods we will use to send the emailwill use to send the email

The *Transport classes all implement this and use their The *Transport classes all implement this and use their implementations of the public methods to send the email differentlyimplementations of the public methods to send the email differently

Our email code doesn’t care about if its given a SmtpTransport or Our email code doesn’t care about if its given a SmtpTransport or PostmarkappTransport it only cares if they implement the PostmarkappTransport it only cares if they implement the TransportInterfaceTransportInterface

Through polymorphism our Transport classes are both instances of:Through polymorphism our Transport classes are both instances of:

*Transport *Transport

TransportInterfaceTransportInterface

Page 33: Introduction to OOP with PHP

Type hinting to require Type hinting to require an interfacean interface

function myEmailCode(TransportInterface $transport, $email){

$transport->setEmail($email);if( ! $transport->send() ) {

echo $transport->getErrors();}

}