Intro to OOP and new features in PHP 5.3

Adam Culp
Adam CulpWeb Engineer/Consultant at Rogue Wave
OOP and PHP 5.3


    South Florida PHP Users Group


                       Adam Culp
                      http://www.Geekyboy.com



In this presentation we will talk about OOP, and discuss
  the object model progression in PHP from version 4
  through the newest 5.3.
I apologize in advance, but this will not be in great detail
   though I hope it is enough to help everyone in some
   way.
Procedural? Really?

• PHP was started as a procedural         <?php
                                          function vehicle($wheels, $color, $hp) {
  tool to perform quick tasks.                 // build a car using info provided
  Large adoption brought more                  $car = array(
  users who wanted OOP, so here                              ‘wheels’ => $wheels,
                                                             ‘color’ => $color,
  we are.                                                    ‘hp’ => $hp);
   – Everything went fairly sequential         return $car;
   – Took a fair amount of labor within   }

     code to change values afterward      $car = vehicle(4, ‘red’, 240);
   – Procedural does make sense for       // now continue with code that uses $car
     simple tasks, such as CRON jobs to   If ($car[‘color’] == ‘red’) {
     perform quick tasks.                       echo ‘Your car is red’;
                                          }

                                          ?>

                                          Output:
                                          Your car is red


                                          Possible usage:
                                          Here is the car: <?php print_r($car); ?>
OOP the basics

• PHP 4 brought the introduction            <?php
                                            Interface mobility {
                                                   function setColor($color);
  of oop to PHP.                            }
                                                   function setHorsepower($hp);

   – Application builds an object           class Vehicle implements mobility {
   – Helps with DRY (Don’t repeat                 public $color;
                                                  public $horsepower;
     yourself)                                    function setColor($color) {
   – Simplifies structure, code still can         }
                                                            $this->color = $color;

     be sequential but is more ‘modular’          function setHorsepower($hp) {
   – Helps keep code more readable                }
                                                            $this->horsepower = $hp;

                                            }
   – Object can be manipulated easier
     prior to use of the object             Class Car extends Vehicle {
                                                  public $wheel;

   – We instantiate the class by creating         function addWheel($n) {

     a “new” object, then manipulate the          }
                                                            $this->wheel += $n;

     object by calling the different        }

     “methods” within the class.            $myCar = new Car();
                                            $myCar->setColor(‘red’);
                                            $myCar->setHorsepower(250);
                                            $myCar->addWheel(3);
                                            $myCar->addWheel(1);

                                            print_r($myCar);
                                            ?>

                                            Output:
                                            Car Object([wheel]=>4[color]=>red[horsepower]=>250)
PHP 4 revisit

• PHP 4 had a very basic OOP                 <?php
                                             class Reference {
  presence, and looked something                  var $reference;
  like this ->
                                                  // acted as constructor
   – Variables need to be defined as              function Reference() {
     ‘var’.                                            $this->reference = ‘dictionary’;
   – Constructors carried the same name           }
     as the Class.
                                                  function getReference() {
       • Note: the constructor always runs             return $this->reference;
         “automagically” when the class is        }
         instantiated                        }
   – No visibility
                                             $rt = new Reference();
   – No abstraction                          $reference = $rt->getReference;
   – Very simple and easy to use, but        echo ‘reference:’ . $reference;
     lacked many features of other OOP       ?>
     languages at the time.
                                             Output:
                                             reference: dictionary
PHP 5.0 brought changes

•   With the rollout of PHP 5.0 there were many          <?php
                                                         class Reference {
    changes.                                                    const DEFAULT_LANG = ‘eng’;
     – Protected data with Visibility                          private $reference;
           • Public (default) – accessed and changed           private $lang;

              globally                                         public function __construct(Language $lang) {
                                                                         if($lang ) {
           • Protected – access and changed by                                    $this->lang = $lang->esp;
              direct descendants                                         } else {
                                                                                  $this->lang = DEFAULT_LANG;
           • Private – access and changed within                         }
              class only                                                 $this->reference = ‘dictionary’;
                                                               }
     – Type Hinting – notice how we specify that an
                                                               public function getReference() {
        object of Language is passed to the                              return $this->reference;
        constructor. This means we must create an              }
        object using the Language class first.
                                                               private function setPrivateReference() {
     – Variables no longer need the ‘var’ keyword                        $this->reference = ‘my_dictionary’;
                                                               }
     – Constructor now defined using __construct         }
        call
                                                         class Language {
     – CONSTANT values may now be assigned                      public $esp = ‘Spanish’;
        per-class, cannot be a variable or property or   }

        mathematical operation or function call.         $lang = new Language();
                                                         $rt = new Reference($lang);
                                                         $reference = $rt->getReference;
                                                         echo ‘reference:’ . $reference;
                                                         ?>

                                                         Output:
                                                         Reference: Spanish
PHP 5.0 Abstraction

•   Abstraction                                        <?php
                                                       abstract class Reference {
     – Abstraction, if a class contains any abstract           public $reference;

        methods the class must also be abstract.                  abstract public function read();
     – Abstracted methods must be defined by the                  public function __construct() {
        child class.                                                      $this->reference = ‘dictionary’;
                                                                  }
     – Visibility in the method of the child class
        must be the same, or less, restricted.                    final public function getReference() {
                                                                          return $this->reference;
     – “final” keyword prevents child classes from                }
        overriding a method
                                                                  protected function setProtectedReference($myReference) {
     – “clone” creates a copy of an object rather                         $this->reference = $myReference;
                                                                  }
        than continuing to use the same object.        }

                                                       class Letter extends Reference {
                                                              public function read($personal) {
                                                                        $myDictionary = $personal;

                                                                          parent::setProtectedReference($myDictionary);

                                                                          return $this->reference;
                                                              }
                                                       }

                                                       $rt = new Letter();
                                                       $reference = $rt->read(‘my english dictionary’);
                                                       $rt2 = clone $rt;

                                                       echo ‘reference:’ . $reference;
                                                       ?>

                                                       Output:
                                                       reference: my english dictionary
PHP 5.0 Interfaces

•   Interface                                     <?php
                                                  interface rTemplate
     – Interface, specifies which methods a       {
                                                        public function getReference();
         class must implement.                          public function setProtectedReference();
                                                  }
     – All methods in interface must be public.
     – Multiple interfaces can be implemented     class Reference implements rTemplate {
                                                         public $reference;
         by using comma separation
                                                          public function __construct() {
     – Interface may contain a CONSTANT,                          $this->reference = ‘dictionary’;
         but may not be overridden by                     }
         implementing class                               public function getReference() {
                                                                  return $this->reference;
                                                          }

                                                          protected function setProtectedReference($myReference) {
                                                                 $this->reference = $myReference;
                                                          }
                                                  }

                                                  $rt = new Letter();
                                                  $reference = $rt->getReference();

                                                  echo ‘reference:’ . $reference;
                                                  ?>

                                                  Output:
                                                  reference: dictionary
PHP 5.0 Exceptions

•                                              <?php
    Additional features with PHP 5.            function inverse($x) {
     – Exceptions – throwing an exception          if (!$x) {
                                                            throw new Exception(‘Division by zero.’);
       to gracefully error out, while              } else {
       continuing to execute the rest of the                return 1/$x;
       script even after the error.                }
                                               }
         • Notice how we still get ‘Hello
           World’ even after an exception      try {
           caused by ‘Division by zero’.            echo inverse(5) . “n”;
                                                    echo inverse(0) . “n”; // trigger exception
     – Exceptions can then be caught for       } catch (Exception $e) {
       logging, etc.                                echo ‘Caught exception: ‘, $e->getMessage(), “n”;
                                               }

                                               // continue execution
                                               echo ‘Hello World’;
                                               ?>

                                               Output:
                                               0.2
                                               Caught exception: Division by zero.
                                               Hello World
Finally, PHP 5.3 features

•   Additional features with PHP 5.3
     – Namespaces
     – Late Static Bindings
     – Jump labels (goto)
     – Closures
     – __callStatic() and __invoke()
     – Class Constants
     – Nowdoc syntax supported
     – Use Heredocs to initialize static
       variables and class properties
     – Heredocs with double quotes
     – Ternary operator shortcut
     – HTTP status 200 to 399 = success
     – Dynamic access to static methods
     – Exception nesting
     – mail() logging of sent email
Namespaces

•   Namespaces                                   <?php
                                                 declare (encoding=‘UTF-8’);
     – Help create a new layer of code           namespace automobile;
       encapsulation.                            class Automobile {
         • Keep properties from colliding              function setType($type) {
                                                                echo __NAMESPACE__ . “n”;
           between areas of your code                  }
         • Only classes, interfaces, functions   }

           and constants are affected            namespace automobilecar;
     – Anything that does not have a             class Car {
       namespace is considered in the                  function toyota() {
                                                                echo “test driven”;
       Global namespace (namespace =                   }
       “”)                                       }

     – Namespace must be declared first          $car = new Car
                                                 $car->toyota();
       (except ‘declare’ statement)
                                                 // OR you can use the namespace
     – Can define multiple namespaces in
                                                 $auto = new automobilecarCar;
       the same file.                            $auto->toyota();

                                                 ?>

                                                 Output:
                                                 test drive
                                                 test drive
Namespaces – cont.

•   Namespaces – cont.                          <?php
                                                namespace automobile;
     – You can define that something be         class Automobile {
       used in the “Global” namespace by              function setType($type) {
                                                        echo __NAMESPACE__ . “n”;
       enclosing a non-labeled namespace              }
       in {} brackets. (Note: if you have       }

       multiple namespaces in the same          namespace automobilecar;
       file they must all use this notation.)   use automobile as auto;
     – Use namespaces from within other         class Car {
       namespaces, along with aliasing                function toyota() {
                                                        echo “test driven”;
                                                      }
                                                }

                                                namespace {
                                                    //global code, for this to work the examples above would also
                                                    need to use bracketed syntax
                                                }

                                                $automobile = new autoAutomobile;
                                                $automobile->setType(‘none’);
                                                ?>

                                                Output:
                                                automobile
Late Static Bindings

•   Late Static Binding                    <?php
                                           class Automobile {
     – Stores the class name of the last         private function type() {
                                                   echo “Success!n”;
        “non-forwarded call”.                    }

                                                public function test() {
                                                  $this->type();
                                                  static::type();
                                                }
                                           }

                                           class Car extends Automobile {
                                                 // empty
                                           }

                                           Class Truck extends Automobile {
                                                 private function type() {
                                                   // empty
                                                 }
                                           }

                                           $car = new Car;
                                           $car->test();
                                           $truck = new Truck;
                                           $truck->test(); //fails because there is no test() in Truck
                                           ?>

                                           Output:
                                           Success!
                                           Success!
                                           Success!
                                           Fatal error: Call to private method Truck::type() from context
                                                 ‘Automobile’ in {file} on line n
Jump Labels (goto)

•   Jump Labels (goto)                         <?php
     – Used to jump to another section in      // some code here
       the program.
                                               goto a;
     – Target is specified by a label          echo ‘Foo’;
       followed by a colon.
     – Target must be within the same file     // more code here
       and context.
         • Cannot jump out of a function or    a:
           method, and cannot jump into one.
     – Cannot jump into any sort of loop       echo ‘Bar’;
       or switch structure, but may jump       ?>
       out.




                                               Output:
                                               Bar
Closures (Anonymous functions)

•   Closures (Anonymous functions)            <?php
                                              class Cart {
     – Allows the creation of functions             protected $products = array();
                                                    const PRICE_SHIRT = 20.00;
       which have no specific name.                 const PRICE_SCARF = 4.00;

     – Most useful as the value of callback        public function order() {
                                                     $this->products[‘shirt’] = 2;
       parameters.                                   $this->products[‘scarf’] = 3;
                                                   }
     – Can be used as the value of a
       variable.                                   public function getTotal($tax) {
                                                    $total = 0.00;
     – Can inherit variables from the                  $callback = function ($quantity, $product) use ($tax, &$total) {
       parent scope. (Not the same as                         $pricePerItem =
                                                              constant(__CLASS__ . “::PRICE_” . strtoupper($product));
       using global variables)
                                                              $total += ($pricePerItem * $quantity) * ($tax +1.0);
                                                       };
                                                       array_walk($this->products, $callback);

                                                       return round($total, 2);
                                                   }
                                              }
                                              ?>

                                              Output:
                                              55.64
Nested Exceptions

•   Nested Exceptions                           <?php
                                                class MyException extends Exception {}
     – Now your criteria within a “try” can
       also have another “try” nested           class Test {
       within, thus causing two levels of           public function testing() {
       failure to caught for further logging.         try {
                                                            try {
                                                                  throw new MyException(‘foo!’);
                                                            } catch (MyException $e) {
                                                                  throw $e;
                                                            }
                                                      } catch (Exception $e) {
                                                            var_dump($e->getMessage());
                                                      }
                                                    }
                                                }

                                                $foo = new Test;
                                                $foo->testing();
                                                ?>

                                                Output:
                                                String(4) “foo!”
New magic methods

•   __callStatic()
     – Used during overloading. Gives          No code to go with this…
       warning to enforce public visibility
       and non-static declaration.              yet. Experiment on your
         • Triggered when invoking
           inaccessible methods in a static     own.
           context.
• __invoke()
     – Called when a script tries to call an
       object as a function
Nowdoc

•   Nowdoc                                 <?php
     – nowdoc is similar to heredoc, but   echo <<<‘EOT’
       no parsing is done inside a nowdoc. My $foo->foo.
                                              name is “$name”. I am printing some
         • Ideal for code snippets or large      Now, I am printing some {$foo->bar[1]}.
           blocks of text without the need for   This should not print a capital ‘A’: /x41
           escaping.                             EOT;
         • Best used with static content.        ?>
     – Uses the same <<< sequence, but
       the following identifier is encosed
       in single quotes.


                                                 Output:
                                                 My name is “$name”. I am printing some
                                                    $foo->foo.
                                                 Now, I am printing some {$foo->bar[1]}.
                                                 This should not print a capital ‘A’: /x41
Heredoc changes

•   Heredoc                                <?php
                                           // Static variables
     – heredoc can now initialize static   function foo() {
       variables and class                     static $bar = <<<“LABEL”
       properties/constants.               Nothing in here…
     – Can now be declared (optional)      LABEL;
                                           }
       using double quotes,
       complementing the nowdoc syntax     // Class properties/constants
       which uses single quotes.           Class foo {
                                               const BAR = <<<FOOBAR
                                           Constant example
                                           FOOBAR;

                                               public $baz = <<<FOOBAR
                                           Property example
                                           FOOBAR
                                           }




                                           ?>
Constants addition

•   Constants addition                     <?php
     – A constant may now be declared      const TEST = ‘bar’;
       outside a class using the ‘const’
       keyword instead of ‘declare’.       Function foo() {
                                             echo ‘foo’;
                                           }

                                           foo();

                                           echo TEST;



                                           ?>
Ternary added shortcut

•                                              <?php
    Constants added shortcut
     – Can now use ternary for simpler         $test = true;
       returns of evaluation.                  // old way
     – Instead of defining the ‘middle’ part   $todo = ($test ? ‘Go’ : ‘Stop’);
       of the operation we simply get a ‘1’    echo $todo;
       if the first expression is true.
       Otherwise we receive what is in the
       third part, as we used to.              // added shortcut
                                               // if $test = true then we get a true flag, otherwise we get
                                                     the second expression as a result
                                               $tada = ($test ?: ‘whatever’);

                                               echo $tada;



                                               ?>

                                               Output (true):
                                               Go1

                                               Output (false):
                                               Stopwhatever
Questions and Resources


    South Florida PHP Users Group


           Adam Culp http://www.Geekyboy.com
           Email: adam@geekyboy.com


                     Resources:
     http://php.net/manual/en/migration53.new-
                     features.php
1 of 21

Recommended

Introduction to PHP OOP by
Introduction to PHP OOPIntroduction to PHP OOP
Introduction to PHP OOPfakhrul hasan
990 views34 slides
Intermediate OOP in PHP by
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHPDavid Stockton
1.7K views90 slides
Intro to OOP PHP and Github by
Intro to OOP PHP and GithubIntro to OOP PHP and Github
Intro to OOP PHP and GithubJo Erik San Jose
1.6K views50 slides
OOP in PHP by
OOP in PHPOOP in PHP
OOP in PHPAlena Holligan
1.1K views40 slides
Php Oop by
Php OopPhp Oop
Php Oopmussawir20
2.7K views14 slides
Object oreinted php | OOPs by
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
4.7K views29 slides

More Related Content

What's hot

Oop in-php by
Oop in-phpOop in-php
Oop in-phpRajesh S
677 views15 slides
Oops in PHP By Nyros Developer by
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperNyros Technologies
577 views21 slides
Oops concepts in php by
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD INDIA
3.6K views44 slides
Class 7 - PHP Object Oriented Programming by
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
2.6K views50 slides
Object oriented programming in php 5 by
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5Sayed Ahmed
433 views52 slides

What's hot(20)

Oop in-php by Rajesh S
Oop in-phpOop in-php
Oop in-php
Rajesh S677 views
Oops concepts in php by CPD INDIA
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA3.6K views
Class 7 - PHP Object Oriented Programming by Ahmed Swilam
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam2.6K views
Object oriented programming in php 5 by Sayed Ahmed
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
Sayed Ahmed433 views
Object Oriented PHP5 by Jason Austin
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
Jason Austin42.5K views
Introduction to perl_ a scripting language by Vamshi Santhapuri
Introduction to perl_ a scripting languageIntroduction to perl_ a scripting language
Introduction to perl_ a scripting language
Vamshi Santhapuri1.3K views
Object Oriented Programming in PHP by Lorna Mitchell
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell3.9K views
09 Object Oriented Programming in PHP #burningkeyboards by Denis Ristic
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
Denis Ristic718 views
Object Oriented Programming with PHP 5 - More OOP by Wildan Maulana
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana5.8K views
Class and Objects in PHP by Ramasubbu .P
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
Ramasubbu .P16.5K views
FFW Gabrovo PMG - PHP OOP Part 3 by Toni Kolev
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
Toni Kolev265 views

Similar to Intro to OOP and new features in PHP 5.3

OOP in PHP by
OOP in PHPOOP in PHP
OOP in PHPTarek Mahmud Apu
606 views37 slides
PHP 5.3 Overview by
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
492 views38 slides
08 Advanced PHP #burningkeyboards by
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboardsDenis Ristic
159 views26 slides
Giới thiệu PHP 7 by
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7ZendVN
787 views30 slides
06-classes.ppt (copy).pptx by
06-classes.ppt (copy).pptx06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptxThắng It
2 views62 slides
PHP OOP Lecture - 02.pptx by
PHP OOP Lecture - 02.pptxPHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptxAtikur Rahman
42 views17 slides

Similar to Intro to OOP and new features in PHP 5.3(20)

PHP 5.3 Overview by jsmith92
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92492 views
08 Advanced PHP #burningkeyboards by Denis Ristic
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
Denis Ristic159 views
Giới thiệu PHP 7 by ZendVN
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
ZendVN787 views
06-classes.ppt (copy).pptx by Thắng It
06-classes.ppt (copy).pptx06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptx
Thắng It2 views
Practical PHP 5.3 by Nate Abele
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
Nate Abele7K views
SPL: The Missing Link in Development by jsmith92
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92733 views
PHP: GraphQL consistency through code generation by Alexander Obukhov
PHP: GraphQL consistency through code generationPHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generation
Alexander Obukhov183 views
Drupaljam xl 2019 presentation multilingualism makes better programmers by Alexander Varwijk
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
Alexander Varwijk121 views
PHP-05-Objects.ppt by rani marri
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
rani marri3 views
The Origin of Lithium by Nate Abele
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
Nate Abele8.4K views
Symfony2, creare bundle e valore per il cliente by Leonardo Proietti
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti1.3K views
02 - Second meetup by EdiPHP
02 - Second meetup02 - Second meetup
02 - Second meetup
EdiPHP179 views
Drupal 8 Services And Dependency Injection by Philip Norton
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
Philip Norton3.1K views
Mastering Namespaces in PHP by Nick Belhomme
Mastering Namespaces in PHPMastering Namespaces in PHP
Mastering Namespaces in PHP
Nick Belhomme16.7K views
OOP by thinkphp
OOPOOP
OOP
thinkphp8.1K views

More from Adam Culp

Hypermedia by
HypermediaHypermedia
HypermediaAdam Culp
651 views42 slides
Putting legacy to REST with middleware by
Putting legacy to REST with middlewarePutting legacy to REST with middleware
Putting legacy to REST with middlewareAdam Culp
2.2K views49 slides
php-1701-a by
php-1701-aphp-1701-a
php-1701-aAdam Culp
217 views50 slides
Release your refactoring superpower by
Release your refactoring superpowerRelease your refactoring superpower
Release your refactoring superpowerAdam Culp
214 views82 slides
Managing Technical Debt by
Managing Technical DebtManaging Technical Debt
Managing Technical DebtAdam Culp
215 views34 slides
Developing PHP Applications Faster by
Developing PHP Applications FasterDeveloping PHP Applications Faster
Developing PHP Applications FasterAdam Culp
482 views56 slides

More from Adam Culp(20)

Hypermedia by Adam Culp
HypermediaHypermedia
Hypermedia
Adam Culp651 views
Putting legacy to REST with middleware by Adam Culp
Putting legacy to REST with middlewarePutting legacy to REST with middleware
Putting legacy to REST with middleware
Adam Culp2.2K views
php-1701-a by Adam Culp
php-1701-aphp-1701-a
php-1701-a
Adam Culp217 views
Release your refactoring superpower by Adam Culp
Release your refactoring superpowerRelease your refactoring superpower
Release your refactoring superpower
Adam Culp214 views
Managing Technical Debt by Adam Culp
Managing Technical DebtManaging Technical Debt
Managing Technical Debt
Adam Culp215 views
Developing PHP Applications Faster by Adam Culp
Developing PHP Applications FasterDeveloping PHP Applications Faster
Developing PHP Applications Faster
Adam Culp482 views
Containing Quality by Adam Culp
Containing QualityContaining Quality
Containing Quality
Adam Culp224 views
Debugging elephpants by Adam Culp
Debugging elephpantsDebugging elephpants
Debugging elephpants
Adam Culp331 views
Zend expressive workshop by Adam Culp
Zend expressive workshopZend expressive workshop
Zend expressive workshop
Adam Culp1.7K views
Expressive Microservice Framework Blastoff by Adam Culp
Expressive Microservice Framework BlastoffExpressive Microservice Framework Blastoff
Expressive Microservice Framework Blastoff
Adam Culp1.6K views
Foundations of Zend Framework by Adam Culp
Foundations of Zend FrameworkFoundations of Zend Framework
Foundations of Zend Framework
Adam Culp975 views
Accidental professional by Adam Culp
Accidental professionalAccidental professional
Accidental professional
Adam Culp811 views
Build great products by Adam Culp
Build great productsBuild great products
Build great products
Adam Culp1K views
Does Your Code Measure Up? by Adam Culp
Does Your Code Measure Up?Does Your Code Measure Up?
Does Your Code Measure Up?
Adam Culp1.8K views
Practical PHP Deployment with Jenkins by Adam Culp
Practical PHP Deployment with JenkinsPractical PHP Deployment with Jenkins
Practical PHP Deployment with Jenkins
Adam Culp11.3K views
Virtualizing Development by Adam Culp
Virtualizing DevelopmentVirtualizing Development
Virtualizing Development
Adam Culp1.5K views
Refactoring Legacy Code by Adam Culp
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
Adam Culp4.3K views
Deprecated: Foundations of Zend Framework 2 by Adam Culp
Deprecated: Foundations of Zend Framework 2Deprecated: Foundations of Zend Framework 2
Deprecated: Foundations of Zend Framework 2
Adam Culp3.4K views
Clean application development tutorial by Adam Culp
Clean application development tutorialClean application development tutorial
Clean application development tutorial
Adam Culp8K views
Refactoring 101 by Adam Culp
Refactoring 101Refactoring 101
Refactoring 101
Adam Culp7.1K views

Recently uploaded

Combining Orchestration and Choreography for a Clean Architecture by
Combining Orchestration and Choreography for a Clean ArchitectureCombining Orchestration and Choreography for a Clean Architecture
Combining Orchestration and Choreography for a Clean ArchitectureThomasHeinrichs1
69 views24 slides
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Safe Software
225 views86 slides
Roadmap to Become Experts.pptx by
Roadmap to Become Experts.pptxRoadmap to Become Experts.pptx
Roadmap to Become Experts.pptxdscwidyatamanew
11 views45 slides
.conf Go 2023 - Data analysis as a routine by
.conf Go 2023 - Data analysis as a routine.conf Go 2023 - Data analysis as a routine
.conf Go 2023 - Data analysis as a routineSplunk
93 views12 slides
PharoJS - Zürich Smalltalk Group Meetup November 2023 by
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023Noury Bouraqadi
120 views17 slides
The details of description: Techniques, tips, and tangents on alternative tex... by
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...BookNet Canada
121 views24 slides

Recently uploaded(20)

Combining Orchestration and Choreography for a Clean Architecture by ThomasHeinrichs1
Combining Orchestration and Choreography for a Clean ArchitectureCombining Orchestration and Choreography for a Clean Architecture
Combining Orchestration and Choreography for a Clean Architecture
ThomasHeinrichs169 views
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software225 views
.conf Go 2023 - Data analysis as a routine by Splunk
.conf Go 2023 - Data analysis as a routine.conf Go 2023 - Data analysis as a routine
.conf Go 2023 - Data analysis as a routine
Splunk93 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi120 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada121 views
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze by NUS-ISS
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng TszeDigital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
NUS-ISS19 views
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... by Vadym Kazulkin
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
Vadym Kazulkin75 views
Transcript: The Details of Description Techniques tips and tangents on altern... by BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada130 views
Data-centric AI and the convergence of data and model engineering: opportunit... by Paolo Missier
Data-centric AI and the convergence of data and model engineering:opportunit...Data-centric AI and the convergence of data and model engineering:opportunit...
Data-centric AI and the convergence of data and model engineering: opportunit...
Paolo Missier34 views
Future of Learning - Khoong Chan Meng by NUS-ISS
Future of Learning - Khoong Chan MengFuture of Learning - Khoong Chan Meng
Future of Learning - Khoong Chan Meng
NUS-ISS33 views
The Importance of Cybersecurity for Digital Transformation by NUS-ISS
The Importance of Cybersecurity for Digital TransformationThe Importance of Cybersecurity for Digital Transformation
The Importance of Cybersecurity for Digital Transformation
NUS-ISS27 views
AI: mind, matter, meaning, metaphors, being, becoming, life values by Twain Liu 刘秋艳
AI: mind, matter, meaning, metaphors, being, becoming, life valuesAI: mind, matter, meaning, metaphors, being, becoming, life values
AI: mind, matter, meaning, metaphors, being, becoming, life values
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb12 views
Future of Learning - Yap Aye Wee.pdf by NUS-ISS
Future of Learning - Yap Aye Wee.pdfFuture of Learning - Yap Aye Wee.pdf
Future of Learning - Yap Aye Wee.pdf
NUS-ISS41 views

Intro to OOP and new features in PHP 5.3

  • 1. OOP and PHP 5.3  South Florida PHP Users Group Adam Culp http://www.Geekyboy.com In this presentation we will talk about OOP, and discuss the object model progression in PHP from version 4 through the newest 5.3. I apologize in advance, but this will not be in great detail though I hope it is enough to help everyone in some way.
  • 2. Procedural? Really? • PHP was started as a procedural <?php function vehicle($wheels, $color, $hp) { tool to perform quick tasks. // build a car using info provided Large adoption brought more $car = array( users who wanted OOP, so here ‘wheels’ => $wheels, ‘color’ => $color, we are. ‘hp’ => $hp); – Everything went fairly sequential return $car; – Took a fair amount of labor within } code to change values afterward $car = vehicle(4, ‘red’, 240); – Procedural does make sense for // now continue with code that uses $car simple tasks, such as CRON jobs to If ($car[‘color’] == ‘red’) { perform quick tasks. echo ‘Your car is red’; } ?> Output: Your car is red Possible usage: Here is the car: <?php print_r($car); ?>
  • 3. OOP the basics • PHP 4 brought the introduction <?php Interface mobility { function setColor($color); of oop to PHP. } function setHorsepower($hp); – Application builds an object class Vehicle implements mobility { – Helps with DRY (Don’t repeat public $color; public $horsepower; yourself) function setColor($color) { – Simplifies structure, code still can } $this->color = $color; be sequential but is more ‘modular’ function setHorsepower($hp) { – Helps keep code more readable } $this->horsepower = $hp; } – Object can be manipulated easier prior to use of the object Class Car extends Vehicle { public $wheel; – We instantiate the class by creating function addWheel($n) { a “new” object, then manipulate the } $this->wheel += $n; object by calling the different } “methods” within the class. $myCar = new Car(); $myCar->setColor(‘red’); $myCar->setHorsepower(250); $myCar->addWheel(3); $myCar->addWheel(1); print_r($myCar); ?> Output: Car Object([wheel]=>4[color]=>red[horsepower]=>250)
  • 4. PHP 4 revisit • PHP 4 had a very basic OOP <?php class Reference { presence, and looked something var $reference; like this -> // acted as constructor – Variables need to be defined as function Reference() { ‘var’. $this->reference = ‘dictionary’; – Constructors carried the same name } as the Class. function getReference() { • Note: the constructor always runs return $this->reference; “automagically” when the class is } instantiated } – No visibility $rt = new Reference(); – No abstraction $reference = $rt->getReference; – Very simple and easy to use, but echo ‘reference:’ . $reference; lacked many features of other OOP ?> languages at the time. Output: reference: dictionary
  • 5. PHP 5.0 brought changes • With the rollout of PHP 5.0 there were many <?php class Reference { changes. const DEFAULT_LANG = ‘eng’; – Protected data with Visibility private $reference; • Public (default) – accessed and changed private $lang; globally public function __construct(Language $lang) { if($lang ) { • Protected – access and changed by $this->lang = $lang->esp; direct descendants } else { $this->lang = DEFAULT_LANG; • Private – access and changed within } class only $this->reference = ‘dictionary’; } – Type Hinting – notice how we specify that an public function getReference() { object of Language is passed to the return $this->reference; constructor. This means we must create an } object using the Language class first. private function setPrivateReference() { – Variables no longer need the ‘var’ keyword $this->reference = ‘my_dictionary’; } – Constructor now defined using __construct } call class Language { – CONSTANT values may now be assigned public $esp = ‘Spanish’; per-class, cannot be a variable or property or } mathematical operation or function call. $lang = new Language(); $rt = new Reference($lang); $reference = $rt->getReference; echo ‘reference:’ . $reference; ?> Output: Reference: Spanish
  • 6. PHP 5.0 Abstraction • Abstraction <?php abstract class Reference { – Abstraction, if a class contains any abstract public $reference; methods the class must also be abstract. abstract public function read(); – Abstracted methods must be defined by the public function __construct() { child class. $this->reference = ‘dictionary’; } – Visibility in the method of the child class must be the same, or less, restricted. final public function getReference() { return $this->reference; – “final” keyword prevents child classes from } overriding a method protected function setProtectedReference($myReference) { – “clone” creates a copy of an object rather $this->reference = $myReference; } than continuing to use the same object. } class Letter extends Reference { public function read($personal) { $myDictionary = $personal; parent::setProtectedReference($myDictionary); return $this->reference; } } $rt = new Letter(); $reference = $rt->read(‘my english dictionary’); $rt2 = clone $rt; echo ‘reference:’ . $reference; ?> Output: reference: my english dictionary
  • 7. PHP 5.0 Interfaces • Interface <?php interface rTemplate – Interface, specifies which methods a { public function getReference(); class must implement. public function setProtectedReference(); } – All methods in interface must be public. – Multiple interfaces can be implemented class Reference implements rTemplate { public $reference; by using comma separation public function __construct() { – Interface may contain a CONSTANT, $this->reference = ‘dictionary’; but may not be overridden by } implementing class public function getReference() { return $this->reference; } protected function setProtectedReference($myReference) { $this->reference = $myReference; } } $rt = new Letter(); $reference = $rt->getReference(); echo ‘reference:’ . $reference; ?> Output: reference: dictionary
  • 8. PHP 5.0 Exceptions • <?php Additional features with PHP 5. function inverse($x) { – Exceptions – throwing an exception if (!$x) { throw new Exception(‘Division by zero.’); to gracefully error out, while } else { continuing to execute the rest of the return 1/$x; script even after the error. } } • Notice how we still get ‘Hello World’ even after an exception try { caused by ‘Division by zero’. echo inverse(5) . “n”; echo inverse(0) . “n”; // trigger exception – Exceptions can then be caught for } catch (Exception $e) { logging, etc. echo ‘Caught exception: ‘, $e->getMessage(), “n”; } // continue execution echo ‘Hello World’; ?> Output: 0.2 Caught exception: Division by zero. Hello World
  • 9. Finally, PHP 5.3 features • Additional features with PHP 5.3 – Namespaces – Late Static Bindings – Jump labels (goto) – Closures – __callStatic() and __invoke() – Class Constants – Nowdoc syntax supported – Use Heredocs to initialize static variables and class properties – Heredocs with double quotes – Ternary operator shortcut – HTTP status 200 to 399 = success – Dynamic access to static methods – Exception nesting – mail() logging of sent email
  • 10. Namespaces • Namespaces <?php declare (encoding=‘UTF-8’); – Help create a new layer of code namespace automobile; encapsulation. class Automobile { • Keep properties from colliding function setType($type) { echo __NAMESPACE__ . “n”; between areas of your code } • Only classes, interfaces, functions } and constants are affected namespace automobilecar; – Anything that does not have a class Car { namespace is considered in the function toyota() { echo “test driven”; Global namespace (namespace = } “”) } – Namespace must be declared first $car = new Car $car->toyota(); (except ‘declare’ statement) // OR you can use the namespace – Can define multiple namespaces in $auto = new automobilecarCar; the same file. $auto->toyota(); ?> Output: test drive test drive
  • 11. Namespaces – cont. • Namespaces – cont. <?php namespace automobile; – You can define that something be class Automobile { used in the “Global” namespace by function setType($type) { echo __NAMESPACE__ . “n”; enclosing a non-labeled namespace } in {} brackets. (Note: if you have } multiple namespaces in the same namespace automobilecar; file they must all use this notation.) use automobile as auto; – Use namespaces from within other class Car { namespaces, along with aliasing function toyota() { echo “test driven”; } } namespace { //global code, for this to work the examples above would also need to use bracketed syntax } $automobile = new autoAutomobile; $automobile->setType(‘none’); ?> Output: automobile
  • 12. Late Static Bindings • Late Static Binding <?php class Automobile { – Stores the class name of the last private function type() { echo “Success!n”; “non-forwarded call”. } public function test() { $this->type(); static::type(); } } class Car extends Automobile { // empty } Class Truck extends Automobile { private function type() { // empty } } $car = new Car; $car->test(); $truck = new Truck; $truck->test(); //fails because there is no test() in Truck ?> Output: Success! Success! Success! Fatal error: Call to private method Truck::type() from context ‘Automobile’ in {file} on line n
  • 13. Jump Labels (goto) • Jump Labels (goto) <?php – Used to jump to another section in // some code here the program. goto a; – Target is specified by a label echo ‘Foo’; followed by a colon. – Target must be within the same file // more code here and context. • Cannot jump out of a function or a: method, and cannot jump into one. – Cannot jump into any sort of loop echo ‘Bar’; or switch structure, but may jump ?> out. Output: Bar
  • 14. Closures (Anonymous functions) • Closures (Anonymous functions) <?php class Cart { – Allows the creation of functions protected $products = array(); const PRICE_SHIRT = 20.00; which have no specific name. const PRICE_SCARF = 4.00; – Most useful as the value of callback public function order() { $this->products[‘shirt’] = 2; parameters. $this->products[‘scarf’] = 3; } – Can be used as the value of a variable. public function getTotal($tax) { $total = 0.00; – Can inherit variables from the $callback = function ($quantity, $product) use ($tax, &$total) { parent scope. (Not the same as $pricePerItem = constant(__CLASS__ . “::PRICE_” . strtoupper($product)); using global variables) $total += ($pricePerItem * $quantity) * ($tax +1.0); }; array_walk($this->products, $callback); return round($total, 2); } } ?> Output: 55.64
  • 15. Nested Exceptions • Nested Exceptions <?php class MyException extends Exception {} – Now your criteria within a “try” can also have another “try” nested class Test { within, thus causing two levels of public function testing() { failure to caught for further logging. try { try { throw new MyException(‘foo!’); } catch (MyException $e) { throw $e; } } catch (Exception $e) { var_dump($e->getMessage()); } } } $foo = new Test; $foo->testing(); ?> Output: String(4) “foo!”
  • 16. New magic methods • __callStatic() – Used during overloading. Gives No code to go with this… warning to enforce public visibility and non-static declaration. yet. Experiment on your • Triggered when invoking inaccessible methods in a static own. context. • __invoke() – Called when a script tries to call an object as a function
  • 17. Nowdoc • Nowdoc <?php – nowdoc is similar to heredoc, but echo <<<‘EOT’ no parsing is done inside a nowdoc. My $foo->foo. name is “$name”. I am printing some • Ideal for code snippets or large Now, I am printing some {$foo->bar[1]}. blocks of text without the need for This should not print a capital ‘A’: /x41 escaping. EOT; • Best used with static content. ?> – Uses the same <<< sequence, but the following identifier is encosed in single quotes. Output: My name is “$name”. I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital ‘A’: /x41
  • 18. Heredoc changes • Heredoc <?php // Static variables – heredoc can now initialize static function foo() { variables and class static $bar = <<<“LABEL” properties/constants. Nothing in here… – Can now be declared (optional) LABEL; } using double quotes, complementing the nowdoc syntax // Class properties/constants which uses single quotes. Class foo { const BAR = <<<FOOBAR Constant example FOOBAR; public $baz = <<<FOOBAR Property example FOOBAR } ?>
  • 19. Constants addition • Constants addition <?php – A constant may now be declared const TEST = ‘bar’; outside a class using the ‘const’ keyword instead of ‘declare’. Function foo() { echo ‘foo’; } foo(); echo TEST; ?>
  • 20. Ternary added shortcut • <?php Constants added shortcut – Can now use ternary for simpler $test = true; returns of evaluation. // old way – Instead of defining the ‘middle’ part $todo = ($test ? ‘Go’ : ‘Stop’); of the operation we simply get a ‘1’ echo $todo; if the first expression is true. Otherwise we receive what is in the third part, as we used to. // added shortcut // if $test = true then we get a true flag, otherwise we get the second expression as a result $tada = ($test ?: ‘whatever’); echo $tada; ?> Output (true): Go1 Output (false): Stopwhatever
  • 21. Questions and Resources  South Florida PHP Users Group Adam Culp http://www.Geekyboy.com Email: adam@geekyboy.com Resources: http://php.net/manual/en/migration53.new- features.php