Introduction to OOP with PHP


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introduction to OOP with PHP

  1. 1. OOP with PHPMichael Peacock
  2. 2. Whats in storeOOP IntroductionClasses and ObjectsEncapsulationPolymorphismInheritance
  3. 3. OOP introduction
  4. 4. Introduction to OOPConcepts are represented as objectsObjects have properties which containinformation about the objectFunctions associated with objects are calledmethods
  5. 5. Classes and objects
  6. 6. Classes and ObjectsA class is a definition of an object. It is a filecontaining: The namespace of the class The name of the class A list of the properties of the class Implementations of any methodsA class becomes an object when it isinstantiated with the new keyword
  7. 7. Defining a class<?phpclass MyClass { // implementation of the class goes in here}
  8. 8. Visibility Public refers to methods and properties which can be accessed or called from both within the object itself and outside of the object (e.g. other files and objects) Private refers to methods and properties which can only be accessed or called from within the object itself Protected refers to methods and properties which can be accessed or called from within the object itself and objects which extend from the object (child objects)
  9. 9. Methods and Properties<?phpclass MyClass { private $someProperty = a default value; private $anotherPropert; public function myMethod() { echo "This is my method being run"; }}
  10. 10. Magic Methods These are methods which are called automatically when certain actions are undertaken, though they can be manually called too. Typically prefixed with two underscores
  11. 11. Magic methods__construct the constructor method; called on an object as soonas it is instantiated. It can accept parameters.__destruct the destructor method; called when an object stopsbeing used/referenced or during shutdown sequence__toString is called when you try to use an object as a string (e.g.echo $my_object) and returns the string representation of theobject__clone is called when you try and clone an object (e.g.$new_object = clone $old_object) useful for dereferencing anyunique IDs, etc.Full list:
  12. 12. With 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"; }}
  13. 13. Working with objectsCreating$my_object = new SomeObject();Accessing propertiesecho $my_object->someProperty; // must bepublicCalling methods$my_object->someMethods(); // must bepublic
  14. 14. $thisWhen working within an object, you accessproperties and methods within the object usingthe $this keyword.For example, consider a method which returnsthe total cost for an order. This needs to add thecost and the delivery cost. Both of these costsare calculated using other methodsreturn $this->calculateCost() + $this->calculateDeliveryCost();
  15. 15. Static Properties can be accessed and methods can be called from anuninstantiated class (i.e. not an object) if they are prefixed with the statickeyword. They are called and accessed with the Scope Resolution Operator (::) class MyClass { public static function printHello() { print “hello”; } } MyClass::printHello();
  16. 16. Class constantsClasses can also contain constants; these aresimilar to properties except they cannot bechanged (unless you edit the php file ofcourse!)const myConstant = “some value”;
  17. 17. Interfaces andImplementsAn interface defines non-private methods (aswell as the number of parameters they accept)that a class which implements the interfacemust haveIf a class specifically implements an interface itmust implement the methods defined, if it doesnot PHP will raise errors.
  18. 18. Defining an interface<?phpinterface MyInterface { public function mustImplementThis(); public function mustImplementThisAsWell($with, $some,$parameters=null);}
  19. 19. Creating a class which implements an interface<?phpclass MyClass implements MyInterface { public function mustImplementThis() { // put some code here } public function mustImplementThisAsWell($with, $some,$parameters=null) { // put some code here }}
  20. 20. ExtendsOne class can extend another. When it doesthis the class inherits properties, methods andconstants from the parent class (the one itextends) - this is where visibility settings areessential.Public and protected properties and methodscan be overridden in the child class; providedthe method names and number of parametersmatch.
  21. 21. Extends 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}
  22. 22. Parent keywordIf you have a method in a child class from whichyou want to access properties or methods inthe parent class, you use the parent keywordwith the scope resolution operator. <?php class Someclass extends Parentclass { public function test() { // this will call the someMethod method // in the Parentclass class echo parent::someMethod(); } }
  23. 23. Abstract classAn abstract class gives us the best of bothworlds; we can define methods which need tobe implemented and we can create methodsand properties which can be extended by achild classAn abstract class is defined using the abstract class cannot beinstantiated directly. Only a class which extendsit can be instantiated.
  24. 24. Defining an abstractclass <?php abstract class MyAbstractClass { protected $someProperty; public function implementMe(); public function implementMeToo(); protected function someMethod() { echo a; } public function __toString() { return $this->someProperty; } }
  25. 25. Using 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}
  26. 26. Encapsulation
  27. 27. Encapsulation With encapsulation the internal representation of anobject is hidden from view outside of the class. Often onlythe object itself is permitted to directly access and modify its properties. This approach means we, the programmer, can have greater control over how these properties are modified.Imagine setting an email address property when a user fills out a contact form. If the property is public, then the property could be any value. If we hide the property and use a setter method, we can put some business logic between the user input and the property such as some validation.
  28. 28. Polymorphism
  29. 29. Polymorphism Polymorphism allows an object, variable or function have more than one form.
  30. 30. Why polymorphismYou have a class (Email) which represents an emailYou have a number of classes which can take an emailobject and send it using a specific technology (e.g.SMTP, sendmail, postmarkapp) lets use SmtpTransportas an exampleWhen you need to send an email you have some code(emailer code) which takes the email, takes theSmtpTransport and links the two togetherIf you want to use your other class,PostmarkappTransport how does “email code” knowhow to work with PostmarkappTransport...these areboth different classes
  31. 31. Why polymorphism...Answer: Interfaces and polymorphismWe have a TransportInterface which defines the public methodswe will use to send the emailThe *Transport classes all implement this and use theirimplementations of the public methods to send the emaildifferentlyOur email code doesn’t care about if its given a SmtpTransport orPostmarkappTransport it only cares if they implement theTransportInterfaceThrough polymorphism our Transport classes are both instancesof: *Transport TransportInterface
  32. 32. Type hinting to requirean interfacefunction myEmailCode(TransportInterface $transport, $email){ $transport->setEmail($email); if( ! $transport->send() ) { echo $transport->getErrors(); }}