SlideShare une entreprise Scribd logo
1  sur  66
Can’t Miss Features of
    PHP 5.3 and 5.4

Jeff Carouth       BCSPHP Sept. 15, 2011


               1
Hi! I am Jeff

Senior Developer at Texas A&M
Author of several magazine articles (php|architect)
Infrequent (lazy) blogger at carouth.com
Lover of progress, innovation, and improvement.
Developing with PHP since ~2003



                       2
About you?


New to PHP?
Using PHP 5.3?
Used PHP yesterday? this afternoon?




                     3
PHP 5.3




   4
What’s all the hubbub?


__DIR__
SPL improvements
Closures / anonymous functions / lambda functions
Namespaces




                     5
__DIR__
“under under durrr”




         6
__DIR__ usefulness

   Cleanup autoloading code.
   That’s about it.



include_once dirname(__FILE__) . "/../myfile.php";


include_once __DIR__ . "/../myfile.php";




                               7
SPL Improvements


SPLFixedArray

SPLDoublyLinkedList

SPLStack and SPLQueue

SPLHeap, SPLMinHeap, SPLMaxHeap

SPLPriorityQueue




                        8
We have shiny new data
structures. Use them instead of
   arrays where appropriate!



               9
Closures



   10
The PHP folk are trying to
     confuse you…



            11
...because not all
anonymous functions are
        closures...


           12
…which aren’t the same as
 lambda expressions or
       functors.


            13
You say semantics? No.
        There is a difference.

(But I’ll step off my soapbox for now. Feel free to ping
                        me later.)

                           14
function() {
    print 'Hello';
};



$myhello = function() {
    print "Hello!";
};

$myhello();




$myhelloname = function($name) {
    print "Hello, " . $name . "!";
};

$myhelloname('BCSPHP');


                             15
function get_closure($name) {
    $person = new stdclass();
    $person->name = $name;

      return function() use($person) {
          print "Hello, " . $person->name . "!";
      };
}

$myhelloclosure = get_closure('Gernonimo');
$myhelloClosure();
// Output: "Hello, Geronimo!"




     $myhelloclosure is said to “close over” the
    $person variable which is within its defined scope.


                                16
Using Lambdas


array_walk, array_map, array_reduce
usort, uasort
array_filter
preg_replace_callback




                17
$fabrics= array(
    array('color'   =>   'blue'),
    array('color'   =>   'red'),
    array('color'   =>   'green'),
    array('color'   =>   'maroon')
);


usort($fabrics, function($a, $b) {
    return strcmp($a['color'], $b['color']);
});




                                 18
// filter based on dynamic criteria
define('MINUTE', 60);
define('HOUR', 3600);
define('DAY', 86400);
define('WEEK', 604800);
$accounts = array(
    array('id' => 1, 'lastActivity'   =>   time()-2*WEEK),
    array('id' => 2, 'lastActivity'   =>   time()-3*DAY),
    array('id' => 3, 'lastActivity'   =>   time()-45*MINUTE),
    array('id' => 4, 'lastActivity'   =>   time()-2*HOUR-5*MINUTE),
    array('id' => 5, 'lastActivity'   =>   time()-5),
    array('id' => 6, 'lastActivity'   =>   time()-3*MINUTE-20),
    array('id' => 7, 'lastActivity'   =>   time()-2*WEEK-3*DAY),
    array('id' => 8, 'lastActivity'   =>   time()-HOUR-33*MINUTE),
    array('id' => 9, 'lastActivity'   =>   time()-5*MINUTE),
);




                               19
$results = array();
$oneweek = time()-WEEK;
foreach ($accounts as $account) {
    if ($account['lastActivity'] > $oneweek) {
        $results[] = $account;
    }
}




$results = array_filter(
    $accounts,
    function($account) {
        return $account['lastActivity'] > time()-WEEK;
    }
);




                             20
$getfilterfunc = function($lower, $upper = 0) {
    $lowerTime = time() - $lower;
    $upperTime = time() - $upper;

    return function($account)
            use($lowerTime, $upperTime) {
        return $account['lastActivity'] >= $lowerTime
            && $account['lastActivity'] <= $upperTime;
    }
}

$pastWeekResults = array_filter(
    $accounts,
    $getfilterfunc(WEEK));
$previousWeekResults = array_filter(
    $accounts,
    $getFilterFunc(2*WEEK, WEEK));



                             21
BOOM!



22
MOAR PRACTICAL


Caching.
Typically you have a load() and save()
method.
Perhaps even a load(), start(), and end()
method.




                   23
class SimpleCache {
    private $_data = array();

    public function load($key) {
        if (!array_key_exists($key, $this->_data)) {
            return false;
        }
        return $this->_data[$key];
    }

    public function save($key, $data) {
        $this->_data[$key] = $data;
    }
}


$cache = new SimpleCache();
if (($data = $cache->load(‘alltags’)) === false) {
    $service = new ExpensiveLookupClass();
    $data = $service->findAllTags();
    $cache->save(‘alltags’, $data);
}

                                24
class SimpleCacheWithClosures {
    protected $_data = array();

    public function load($key, $callback) {
        if (!array_key_exists($key, $this->_data)) {
            $this->_data[$key] = $callback();
        }
        return $this->_data[$key];
    }
}


$cache = new SimpleCacheWithClosures();

$service = new ExpensiveLookupClass();
$data = $cache->load('alltags', function() use($service) {
    return $service->findAllTags();
});



                              25
Functors
Because the rest just wasn’t enough…




                 26
Functors, in simple terms,
are objects that you can call
  as if they are functions.


              27
class Send {
    private function _broadcast() {
        return 'Message sent.';
    }

    public function __invoke() {
        return $this->_broadcast();
    }
}

$send = new Send();
debug_log($send());




                             28
Namespaces


All the cool languages have them.
or perhaps PHP just wants to be JAVA
with all its package glory
after all, we do have PHARs




                       29
Nope. Namespaces solve a
       real need.



           30
The “” Separator



        31
Namespace Benefits


Organization. Both file and code.
Reduce conflicts with other libraries.
Shorten class names.
Readability.




                       32
define("LIBRARYDIR", __DIR__);

class Tamu_Cas_Adapter {
    function auth() { }
}

function tamu_cas_create_client() {
    return new Tamu_Http_Client();
}


namespace TamuCas;
use TamuHttpClient as HttpClient;

const LIBRARYDIR = __DIR__;

class Adapter {
    function auth() { }
}

function create_client() {
    return new HttpClient();
}
                               33
Namespace organization

In /path/to/Tamu.php:
namespace Tamu;



In /path/to/Tamu/Dmc.php
namespace TamuDmc;



In /path/to/Tamu/Auth/Adapter/Cas.php
namespace TamuAuthAdapter;
class Cas { }


                               34
Conflict Resolution

namespace My;
function str_split($string, $split_len = 2) {
    return "Nope. I don't like to split strings.";
}

$splitstr = str_split('The quick brown fox');
// $splitstr = "Nope. I don't like to split strings."

$splitstr = str_split('The quick brown fox');
// $splitstr = array('T', 'h', 'e', ..., 'o', 'x');




                             35
Class name shortening

class Zend_Application_Resource_Cachemanager
    extends Zend_Application_Resource_ResourceAbstract
{
    //...
}



namespace ZendApplicationResource;
class Cachemanager extends ResourceAbstract
{
    //...
}



                              36
Readability by Namespace


require_once "Zend/Http/Client.php";
$client = new Zend_Http_Client();


use ZendHttp;
$client = new Client();


use ZendHttpClient as HttpClient;
$httpClient = new HttpClient();




                             37
Take a deep breath
        38
PHP 5.4



alpha3 was used for demos
beta going to be packaged on Sep 14
(source:php-internals)




                     39
New Features

Closures support $this keyword
Short Array Syntax
Array Dereferencing
Traits
(Debug webserver)

                40
Closures and $this
class HelloWorldPrinter
{
    public function __construct($name) {
        $this->_name = $name;
    }

    public function getPrinter() {
        return function() {
            return "Hello, " . $this->_name . "!";
        };
    }
}


$instance = new HelloWorldPrinter('BCSPHP');
$printer = $instance->getPrinter();

echo $printer();
                             41
Prior to PHP 5.4
Fatal error: Using $this when not in object context in /
Users/jcarouth/Documents/code-bcsphp-092011/
php54closurethis.php on line 14




PHP 5.4.0alpha3 (built Aug 5, 2011)
Hello, BCSPHP!




                              42
Short Array Syntax
          Saving you a few keystrokes
and compute cycles when switching from JavaScript




                       43
Really, who doesn’t love
JavaScript array syntax?



           44
//empty array
$arr = [];

//simple array
$arr = [1, 2, 3];

//"dictionary" array
$arr = ['name' => 'jeff', 'language' => 'php'];

//multi-dimensional
$arr = [['orange', 'blue'], ['black', 'gold']];




                             45
Array Dereferencing
         46
$array = array(1, 2, 3);
$dereference = *$array;




                   Sorry, no pointers.
    All the upset C++ wizards, go have some pizza.




                           47
class UserDataSource
{
    public function getDataForJeff()
    {
        return [
            'id' => 1,
            'name' => 'Jeff Carouth',
            'isAdmin' => true,
        ];
    }
}


$jeff = $store->getDataForJeff();
if ($jeff['isAdmin'] === true) {
    //give him access to all the things
}
                                             PHP <= 5.3
if ($store->getDataForJeff()['isAdmin']) {
    //shorter...but be mindful
}
                             48
                                             PHP >= 5.4
Pitfalls


Dereferencing a non-existent key produces a
NOTICE.
If the function does not return an array,
unexpected behavior.




                       49
Traits!



   50
Definition

Traits is a mechanism for code reuse in single
inheritance languages such as PHP. A Trait is
intended to reduce some limitations of single
inheritance by enabling a developer to reuse
sets of methods freely in several independent
classes living in different class hierarchies. The
semantics of the combination of Traits and
classes is defined in a way, which reduces
complexity and avoids the typical problems
associated with multiple inheritance and Mixins.



                        51
A bit much to
      take in
The important bit is traits
allow developers like you to
increase code reuse and get
around limitations of single-
inheritance.



                                52
Show me the code!

trait Named {
    function name() {
        //function body
    }
}




                          53
class SearchController {
    public function findBook(Book $b) { }

    private function log($message) {
        error_log($message);
    }
}

class AdminController {
    public function grant(User $u, Privilege $p) { }

    private function log($message) {
        error_log($message);
    }
}




                             54
trait Logging {
    private function log($message) {
        error_log($message);
    }
}

class SearchController {
    use Logging;
}

class AdminController {
    use Logging;
}




                             55
namespace TamuTimesModels;
class Story {
    public function setDataStore($store) {
        $this->_ds = $store;
    }

    public function getDataStore() {
        return $this->_ds;
    }
}

class User {
    public function setDataStore($store) {
        $this->_ds = $store;
    }

    public function getDataStore() {
        return $this->_ds;
    }
}


                             56
namespace TamuDmcApp;
trait DataStore {
    public function setDataStore($store) {
        $this->_ds = $store;
    }

    public function getDataStore() {
        return $this->_ds;
    }
}

namespace TamuTimesModels;
use TamuDmcAppDataStore;
class Story {
    use DataStore;
}

class User {
    use DataStore;
}


                              57
namespace BCSPHP;
trait MessageBroadcast {
    public function sendMessage() { }

    abstract private function _formatMessage();
}

class MeetingNotification {
    use MessageBroadcast;

    private function _formatMessage() {
        return "Notice: BCSPHP Meeting " . $this->_date;
    }
}




                              58
Traits are “just compiler
assisted copy and paste.”
      - Stefan Marr, PHP Internals Mailing List, Nov 2010




                  59
Built-in Development Server




             60
DEMO

php -S 0.0.0.0:8080 -t /path/to/docroot




                        61
Caveat

       Routing must be handled with a separate
       router.php script.

if (file_exists(__DIR__ . '/' . $_SERVER['REQUEST_URI'])) {
    return false; // serve the requested resource as-is.
} else {
    include_once 'index.php';
}


if (php_sapi_name() == 'cli-server') {
    /* route static assets and return false */
}

                             62
What you can do now:


(more like what you should do)
Test PHP 5.4 — http://qa.php.net
Run    make test
TEST YOUR APPS against PHP 5.4-alpha/beta/RC




                     63
That’s all folks!

QUESTIONS?

@jcarouth

jcarouth@gmail.com

jeffcarouth.info



                     64
Have feedback?

http://joind.in/3716




          65
Resources


Enygma’s PHP 5.3 example code
http://bit.ly/q9Eu36
Elazar’s benchmarks of SPL features in PHP 5.3
http://bit.ly/nKsbvQ
PHP documentation on the built-in web server
http://bit.ly/rc26l0



                      66

Contenu connexe

Tendances

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks Damien Seguy
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language TriviaNikita Popov
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Fabien Potencier
 
What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16Ricardo Signes
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Contextlichtkind
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console componentHugo Hamon
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 

Tendances (20)

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 
Symfony2 - OSIDays 2010
Symfony2 - OSIDays 2010Symfony2 - OSIDays 2010
Symfony2 - OSIDays 2010
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
PhpBB meets Symfony2
PhpBB meets Symfony2PhpBB meets Symfony2
PhpBB meets Symfony2
 
What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Context
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Symfony2 - extending the console component
Symfony2 - extending the console componentSymfony2 - extending the console component
Symfony2 - extending the console component
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 

En vedette

Tugas praktikum algoritma modul 1 faisal al zamar
Tugas praktikum algoritma modul 1 faisal al zamarTugas praktikum algoritma modul 1 faisal al zamar
Tugas praktikum algoritma modul 1 faisal al zamarFaisal Zamar
 
Networking tutorial
Networking tutorialNetworking tutorial
Networking tutorialajaymane22
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Vidyasagar Mundroy
 
Directory Structure Changes in Laravel 5.3
Directory Structure Changes in Laravel 5.3Directory Structure Changes in Laravel 5.3
Directory Structure Changes in Laravel 5.3DHRUV NATH
 
Test studio webinar march 2013
Test studio webinar march 2013Test studio webinar march 2013
Test studio webinar march 2013Dhananjay Kumar
 
Computer networking
Computer networkingComputer networking
Computer networkingtdsparks3
 
Asp.Net Mvc 5 Identity
Asp.Net Mvc 5 IdentityAsp.Net Mvc 5 Identity
Asp.Net Mvc 5 IdentityÜnal Ün
 
Computer Networking Specialist
Computer Networking SpecialistComputer Networking Specialist
Computer Networking Specialistcarlsandburg
 
Laravel 5 Tutorial : Membuat Blog Sederhana dengan Laravel 5.3
Laravel 5 Tutorial : Membuat Blog Sederhana dengan Laravel 5.3Laravel 5 Tutorial : Membuat Blog Sederhana dengan Laravel 5.3
Laravel 5 Tutorial : Membuat Blog Sederhana dengan Laravel 5.3harisonmtd
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction ManagementDenise McInerney
 
Computer networking wire color powerpoint templates
Computer networking wire color powerpoint templatesComputer networking wire color powerpoint templates
Computer networking wire color powerpoint templateshttp://www.slideworld.com/
 
New Features in PHP 5.3
New Features in PHP 5.3New Features in PHP 5.3
New Features in PHP 5.3Bradley Holt
 
Php7 傳說中的第七隻大象
Php7 傳說中的第七隻大象Php7 傳說中的第七隻大象
Php7 傳說中的第七隻大象bobo52310
 

En vedette (20)

Select Queries
Select QueriesSelect Queries
Select Queries
 
Tugas praktikum algoritma modul 1 faisal al zamar
Tugas praktikum algoritma modul 1 faisal al zamarTugas praktikum algoritma modul 1 faisal al zamar
Tugas praktikum algoritma modul 1 faisal al zamar
 
Networking tutorial
Networking tutorialNetworking tutorial
Networking tutorial
 
Sql server concurrency
Sql server concurrencySql server concurrency
Sql server concurrency
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 
Build HTML5 Sites/Apps with Kendo UI Core
Build HTML5 Sites/Apps with Kendo UI CoreBuild HTML5 Sites/Apps with Kendo UI Core
Build HTML5 Sites/Apps with Kendo UI Core
 
Directory Structure Changes in Laravel 5.3
Directory Structure Changes in Laravel 5.3Directory Structure Changes in Laravel 5.3
Directory Structure Changes in Laravel 5.3
 
Test studio webinar march 2013
Test studio webinar march 2013Test studio webinar march 2013
Test studio webinar march 2013
 
Computer networking
Computer networkingComputer networking
Computer networking
 
Lap Around ASP.NET MVC 5
Lap Around ASP.NET MVC 5Lap Around ASP.NET MVC 5
Lap Around ASP.NET MVC 5
 
Asp.Net Mvc 5 Identity
Asp.Net Mvc 5 IdentityAsp.Net Mvc 5 Identity
Asp.Net Mvc 5 Identity
 
Computer Networking Specialist
Computer Networking SpecialistComputer Networking Specialist
Computer Networking Specialist
 
Laravel 5 Tutorial : Membuat Blog Sederhana dengan Laravel 5.3
Laravel 5 Tutorial : Membuat Blog Sederhana dengan Laravel 5.3Laravel 5 Tutorial : Membuat Blog Sederhana dengan Laravel 5.3
Laravel 5 Tutorial : Membuat Blog Sederhana dengan Laravel 5.3
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction Management
 
Sql intro
Sql introSql intro
Sql intro
 
Computer networking wire color powerpoint templates
Computer networking wire color powerpoint templatesComputer networking wire color powerpoint templates
Computer networking wire color powerpoint templates
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
 
New Features in PHP 5.3
New Features in PHP 5.3New Features in PHP 5.3
New Features in PHP 5.3
 
Php7 傳說中的第七隻大象
Php7 傳說中的第七隻大象Php7 傳說中的第七隻大象
Php7 傳說中的第七隻大象
 
Sql DML
Sql DMLSql DML
Sql DML
 

Similaire à Can't Miss Features of PHP 5.3 and 5.4

Similaire à Can't Miss Features of PHP 5.3 and 5.4 (20)

PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 
PHP Conference Asia 2016
PHP Conference Asia 2016PHP Conference Asia 2016
PHP Conference Asia 2016
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Oops in php
Oops in phpOops in php
Oops in php
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Smelling your code
Smelling your codeSmelling your code
Smelling your code
 
PHP 5.4
PHP 5.4PHP 5.4
PHP 5.4
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 

Dernier

Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfAnna Loughnan Colquhoun
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 

Dernier (20)

Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdf
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 

Can't Miss Features of PHP 5.3 and 5.4

  • 1. Can’t Miss Features of PHP 5.3 and 5.4 Jeff Carouth BCSPHP Sept. 15, 2011 1
  • 2. Hi! I am Jeff Senior Developer at Texas A&M Author of several magazine articles (php|architect) Infrequent (lazy) blogger at carouth.com Lover of progress, innovation, and improvement. Developing with PHP since ~2003 2
  • 3. About you? New to PHP? Using PHP 5.3? Used PHP yesterday? this afternoon? 3
  • 5. What’s all the hubbub? __DIR__ SPL improvements Closures / anonymous functions / lambda functions Namespaces 5
  • 7. __DIR__ usefulness Cleanup autoloading code. That’s about it. include_once dirname(__FILE__) . "/../myfile.php"; include_once __DIR__ . "/../myfile.php"; 7
  • 8. SPL Improvements SPLFixedArray SPLDoublyLinkedList SPLStack and SPLQueue SPLHeap, SPLMinHeap, SPLMaxHeap SPLPriorityQueue 8
  • 9. We have shiny new data structures. Use them instead of arrays where appropriate! 9
  • 10. Closures 10
  • 11. The PHP folk are trying to confuse you… 11
  • 12. ...because not all anonymous functions are closures... 12
  • 13. …which aren’t the same as lambda expressions or functors. 13
  • 14. You say semantics? No. There is a difference. (But I’ll step off my soapbox for now. Feel free to ping me later.) 14
  • 15. function() { print 'Hello'; }; $myhello = function() { print "Hello!"; }; $myhello(); $myhelloname = function($name) { print "Hello, " . $name . "!"; }; $myhelloname('BCSPHP'); 15
  • 16. function get_closure($name) { $person = new stdclass(); $person->name = $name; return function() use($person) { print "Hello, " . $person->name . "!"; }; } $myhelloclosure = get_closure('Gernonimo'); $myhelloClosure(); // Output: "Hello, Geronimo!" $myhelloclosure is said to “close over” the $person variable which is within its defined scope. 16
  • 17. Using Lambdas array_walk, array_map, array_reduce usort, uasort array_filter preg_replace_callback 17
  • 18. $fabrics= array( array('color' => 'blue'), array('color' => 'red'), array('color' => 'green'), array('color' => 'maroon') ); usort($fabrics, function($a, $b) { return strcmp($a['color'], $b['color']); }); 18
  • 19. // filter based on dynamic criteria define('MINUTE', 60); define('HOUR', 3600); define('DAY', 86400); define('WEEK', 604800); $accounts = array( array('id' => 1, 'lastActivity' => time()-2*WEEK), array('id' => 2, 'lastActivity' => time()-3*DAY), array('id' => 3, 'lastActivity' => time()-45*MINUTE), array('id' => 4, 'lastActivity' => time()-2*HOUR-5*MINUTE), array('id' => 5, 'lastActivity' => time()-5), array('id' => 6, 'lastActivity' => time()-3*MINUTE-20), array('id' => 7, 'lastActivity' => time()-2*WEEK-3*DAY), array('id' => 8, 'lastActivity' => time()-HOUR-33*MINUTE), array('id' => 9, 'lastActivity' => time()-5*MINUTE), ); 19
  • 20. $results = array(); $oneweek = time()-WEEK; foreach ($accounts as $account) { if ($account['lastActivity'] > $oneweek) { $results[] = $account; } } $results = array_filter( $accounts, function($account) { return $account['lastActivity'] > time()-WEEK; } ); 20
  • 21. $getfilterfunc = function($lower, $upper = 0) { $lowerTime = time() - $lower; $upperTime = time() - $upper; return function($account) use($lowerTime, $upperTime) { return $account['lastActivity'] >= $lowerTime && $account['lastActivity'] <= $upperTime; } } $pastWeekResults = array_filter( $accounts, $getfilterfunc(WEEK)); $previousWeekResults = array_filter( $accounts, $getFilterFunc(2*WEEK, WEEK)); 21
  • 23. MOAR PRACTICAL Caching. Typically you have a load() and save() method. Perhaps even a load(), start(), and end() method. 23
  • 24. class SimpleCache { private $_data = array(); public function load($key) { if (!array_key_exists($key, $this->_data)) { return false; } return $this->_data[$key]; } public function save($key, $data) { $this->_data[$key] = $data; } } $cache = new SimpleCache(); if (($data = $cache->load(‘alltags’)) === false) { $service = new ExpensiveLookupClass(); $data = $service->findAllTags(); $cache->save(‘alltags’, $data); } 24
  • 25. class SimpleCacheWithClosures { protected $_data = array(); public function load($key, $callback) { if (!array_key_exists($key, $this->_data)) { $this->_data[$key] = $callback(); } return $this->_data[$key]; } } $cache = new SimpleCacheWithClosures(); $service = new ExpensiveLookupClass(); $data = $cache->load('alltags', function() use($service) { return $service->findAllTags(); }); 25
  • 26. Functors Because the rest just wasn’t enough… 26
  • 27. Functors, in simple terms, are objects that you can call as if they are functions. 27
  • 28. class Send { private function _broadcast() { return 'Message sent.'; } public function __invoke() { return $this->_broadcast(); } } $send = new Send(); debug_log($send()); 28
  • 29. Namespaces All the cool languages have them. or perhaps PHP just wants to be JAVA with all its package glory after all, we do have PHARs 29
  • 30. Nope. Namespaces solve a real need. 30
  • 32. Namespace Benefits Organization. Both file and code. Reduce conflicts with other libraries. Shorten class names. Readability. 32
  • 33. define("LIBRARYDIR", __DIR__); class Tamu_Cas_Adapter { function auth() { } } function tamu_cas_create_client() { return new Tamu_Http_Client(); } namespace TamuCas; use TamuHttpClient as HttpClient; const LIBRARYDIR = __DIR__; class Adapter { function auth() { } } function create_client() { return new HttpClient(); } 33
  • 34. Namespace organization In /path/to/Tamu.php: namespace Tamu; In /path/to/Tamu/Dmc.php namespace TamuDmc; In /path/to/Tamu/Auth/Adapter/Cas.php namespace TamuAuthAdapter; class Cas { } 34
  • 35. Conflict Resolution namespace My; function str_split($string, $split_len = 2) { return "Nope. I don't like to split strings."; } $splitstr = str_split('The quick brown fox'); // $splitstr = "Nope. I don't like to split strings." $splitstr = str_split('The quick brown fox'); // $splitstr = array('T', 'h', 'e', ..., 'o', 'x'); 35
  • 36. Class name shortening class Zend_Application_Resource_Cachemanager extends Zend_Application_Resource_ResourceAbstract { //... } namespace ZendApplicationResource; class Cachemanager extends ResourceAbstract { //... } 36
  • 37. Readability by Namespace require_once "Zend/Http/Client.php"; $client = new Zend_Http_Client(); use ZendHttp; $client = new Client(); use ZendHttpClient as HttpClient; $httpClient = new HttpClient(); 37
  • 38. Take a deep breath 38
  • 39. PHP 5.4 alpha3 was used for demos beta going to be packaged on Sep 14 (source:php-internals) 39
  • 40. New Features Closures support $this keyword Short Array Syntax Array Dereferencing Traits (Debug webserver) 40
  • 41. Closures and $this class HelloWorldPrinter { public function __construct($name) { $this->_name = $name; } public function getPrinter() { return function() { return "Hello, " . $this->_name . "!"; }; } } $instance = new HelloWorldPrinter('BCSPHP'); $printer = $instance->getPrinter(); echo $printer(); 41
  • 42. Prior to PHP 5.4 Fatal error: Using $this when not in object context in / Users/jcarouth/Documents/code-bcsphp-092011/ php54closurethis.php on line 14 PHP 5.4.0alpha3 (built Aug 5, 2011) Hello, BCSPHP! 42
  • 43. Short Array Syntax Saving you a few keystrokes and compute cycles when switching from JavaScript 43
  • 44. Really, who doesn’t love JavaScript array syntax? 44
  • 45. //empty array $arr = []; //simple array $arr = [1, 2, 3]; //"dictionary" array $arr = ['name' => 'jeff', 'language' => 'php']; //multi-dimensional $arr = [['orange', 'blue'], ['black', 'gold']]; 45
  • 47. $array = array(1, 2, 3); $dereference = *$array; Sorry, no pointers. All the upset C++ wizards, go have some pizza. 47
  • 48. class UserDataSource { public function getDataForJeff() { return [ 'id' => 1, 'name' => 'Jeff Carouth', 'isAdmin' => true, ]; } } $jeff = $store->getDataForJeff(); if ($jeff['isAdmin'] === true) { //give him access to all the things } PHP <= 5.3 if ($store->getDataForJeff()['isAdmin']) { //shorter...but be mindful } 48 PHP >= 5.4
  • 49. Pitfalls Dereferencing a non-existent key produces a NOTICE. If the function does not return an array, unexpected behavior. 49
  • 50. Traits! 50
  • 51. Definition Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way, which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins. 51
  • 52. A bit much to take in The important bit is traits allow developers like you to increase code reuse and get around limitations of single- inheritance. 52
  • 53. Show me the code! trait Named { function name() { //function body } } 53
  • 54. class SearchController { public function findBook(Book $b) { } private function log($message) { error_log($message); } } class AdminController { public function grant(User $u, Privilege $p) { } private function log($message) { error_log($message); } } 54
  • 55. trait Logging { private function log($message) { error_log($message); } } class SearchController { use Logging; } class AdminController { use Logging; } 55
  • 56. namespace TamuTimesModels; class Story { public function setDataStore($store) { $this->_ds = $store; } public function getDataStore() { return $this->_ds; } } class User { public function setDataStore($store) { $this->_ds = $store; } public function getDataStore() { return $this->_ds; } } 56
  • 57. namespace TamuDmcApp; trait DataStore { public function setDataStore($store) { $this->_ds = $store; } public function getDataStore() { return $this->_ds; } } namespace TamuTimesModels; use TamuDmcAppDataStore; class Story { use DataStore; } class User { use DataStore; } 57
  • 58. namespace BCSPHP; trait MessageBroadcast { public function sendMessage() { } abstract private function _formatMessage(); } class MeetingNotification { use MessageBroadcast; private function _formatMessage() { return "Notice: BCSPHP Meeting " . $this->_date; } } 58
  • 59. Traits are “just compiler assisted copy and paste.” - Stefan Marr, PHP Internals Mailing List, Nov 2010 59
  • 61. DEMO php -S 0.0.0.0:8080 -t /path/to/docroot 61
  • 62. Caveat Routing must be handled with a separate router.php script. if (file_exists(__DIR__ . '/' . $_SERVER['REQUEST_URI'])) { return false; // serve the requested resource as-is. } else { include_once 'index.php'; } if (php_sapi_name() == 'cli-server') { /* route static assets and return false */ } 62
  • 63. What you can do now: (more like what you should do) Test PHP 5.4 — http://qa.php.net Run make test TEST YOUR APPS against PHP 5.4-alpha/beta/RC 63
  • 66. Resources Enygma’s PHP 5.3 example code http://bit.ly/q9Eu36 Elazar’s benchmarks of SPL features in PHP 5.3 http://bit.ly/nKsbvQ PHP documentation on the built-in web server http://bit.ly/rc26l0 66

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. PHP 5.3.0 released June 30, 2009.\nBugfixes and security patches in 5.3.1-5.3.6 (11/2009-3/2011)\n5.3.7 released on Aug. 18, 2011. focused on improving stability\n5.3.8 released shortly after (Aug 23) to fix two issues introduced in .7\n
  5. Listed in an ascending level of interesting-ness.\nMagic Constants: LINE, FILE, DIR, FUNCTION, CLASS, METHOD, NAMESPACE\nStandard PHP Library\n
  6. \n
  7. __DIR__ does not include a trailing space\n
  8. Sometimes marginal differences in throughput (execs/sec), but memory consumption is generally lower with respect to dataset size (num elements)\n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. This isn&amp;#x2019;t a terribly intriguing use case, so let&amp;#x2019;s look at a more practical example.\n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. Cannot do use(new Obj() as $s) :-(\n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. Just get over it. Embrace the backslash.\n
  32. Organize OO code into self-contained units.\nEver heard of the global namespace pollution issue?\nPEAR naming convention\nImports and aliases.\n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. Before 5.4 you cannot refer to the object instance that created the closure.\nEXAMPLE\n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n