Introducing PHP Latest Updates
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Introducing PHP Latest Updates

on

  • 567 views

 

Statistics

Views

Total Views
567
Views on SlideShare
567
Embed Views
0

Actions

Likes
0
Downloads
14
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Introducing PHP Latest Updates Presentation Transcript

  • 1. Introducing PHP Latest Updates Presenter Iftekhar Ahmed Eather Software Engineer Divine IT Limited Source php.net, slideshare.com, wiki, google, git document and others 1
  • 2. Topics • PHP 5.3 • PHP 5.4 • PHP 5.5 • PSR • FlexiGrid 2
  • 3. PHP 5.3 Released Date 30-Jun-2009 3
  • 4. What‟s New in PHP 5.3 • • Late Static Binding • Closures • NOWDOC • Ternary short cut • Jump Label • Operators, Syntax, Magic Methods, Constants & php.ini • Garbage collector • Date and Time • 4 Namespaces Others
  • 5. Namespaces Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code. Example: <?php namespace Foo; const ANSWER = 42; class C { /* ... */ } function f() { } echo FooANSWER; new FooC(); Foof(); ?> 5
  • 6. __ NAMESPACE__ <?php namespace MyProject; echo '"', __NAMESPACE__, '"'; // outputs "MyProject" ?> 6
  • 7. Class Resolution namespace MyFrameworksomeModule; class PdoException { } new PdoException(); // MyFrameworkmyModule new PdoException(); // ext/pdo new DateTime(); // class not found! new DateTime(); // works 7
  • 8. Aliasing foo/bar.php: <?php namespace foobar; class class1 {} // foobarclass1 ?> some/code.php: <?php use foobar as baz; use foobarclass1 as zomg; new bazclass2(); new zomg(); ?> 8
  • 9. Late Static Binding Late static bindings can be used to reference the called class in a context of static inheritance. Example: <?php class A { public static function who() { echo __CLASS__; } public static function test() { static::who(); // Here comes Late Static Bindings } } class B extends A { public static function who() { echo __CLASS__; } } 9 B::test(); // output B ?>
  • 10. self vs static with LSB class Base { public static function m() { self::printName(); class Extended extends Base { static::printName(); static function printName() } { static function printName() echo __CLASS__; { } echo __CLASS__; } Extended::m(); // Output: Base Extended } Base::m(); 10 // Output: Base Base
  • 11. Closures Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Example: <?php $greet = function($name) { printf("Hello %srn", $name); }; $greet('World'); $greet('PHP'); ?> 11
  • 12. NOWDOC & HEREDOC Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. Example: NOWDOC echo <<<'BAI' Price: $US 375 BAI; Price: $US 375 HEREDOC $US = 10 echo <<<"BAI" Price: $US 375 BAI; Price: 10 375 12
  • 13. Ternary short cut Allows quick retrieval of a non-empty value from 2 values and/or expressions Example: $a = true ?: false; // true $a = false ?: true; // true $a = "" ?: 1; // 1 $a = 0 ?: 2; // 2 $a = array() ?: array(1); // array(1); $a = strlen("") ?: strlen("a"); // 1 13
  • 14. Jump: Goto The goto operator can be used to jump to another section in the program Example: if($i < 100) { goto durr; } durr: $i++; 14
  • 15. Operators, Syntax, Magic Methods & Constants __callStatic(): __call() equivalent, but for static methods. Example: class helper { static function __callStatic($name, $args) { echo $name.'('.implode(',', $args).')'; } } helper::test("foo","bar"); // test(foo,bar) Dynamic Static Calls: Example: class helper { static function foo() { echo __METHOD__; } } $a = "helper"; $b = "foo"; $a::$b(); // helper::foo 15 Dynamic function/method calls are kinds of slow
  • 16. Operators, Syntax, Magic Methods & Constants __DIR__: // old: function call, conditional include include(dirname(__FILE__) . '/brother.php'); // new: magic constant, no conditional include include(__DIR__ . '/brother.php'); Php_ini: This list includes the php.ini sections you can set to configure your PHP setup on a per Host or Path basis. These sections are optional. These sections don't directly affect PHP. They are used to group other php.ini directives together and to get them to act upon a particular host or on a particular path Example: 16 [HOST=dev.site.com] error_reporting = E_ALL display_errors = On [PATH=/home/site/public/secure] auto_prepend_file=security.php
  • 17. Garbage Collector Memory cleanup for complex and long scripts that need to free-up memory before the end of execution cycle. gc_enable(); // Enable Garbage Collector var_dump(gc_enabled()); // true var_dump(gc_collect_cycles()); // # of elements cleaned up gc_disable(); // Disable Garbage Collector 17
  • 18. Date Extension Additions Controllable strtotime() via date_create_from_format() $date = strtotime("08-01-07 00:00:00"); var_dump(date("Y-m-d", $date)); // string(10) "2008-01-07" $date = date_create_from_format("m-d-y", "08-01-07"); var_dump($date->format('Y-m-d')); // string(10) "2007-08-01“ Added date_get_last_errors() that returns errors and warnings in date parsing. array(4) { ["warning_count"] => int(0) ["warnings"] => array(0) { } ["error_count"] => int(2) ["errors"]=> array(2) { [2]=> string(40) "The separation symbol could not be found" [6]=> string(13) "Trailing data” } 18 }
  • 19. E_DEPRECATED • • Part of E_ALL • E_USER_DEPRECATED for userland errors • 19 New error level to indicated deprecated stuff scheduled for removal in later releases Run-time notices. Enable this to receive warnings about code that will not work in future versions.
  • 20. New Extensions • intl • sqlite3 • mysqlnd • phar • fileinfo • enchant Over 140 bug fixes Improved Windows support 20
  • 21. Removed Extensions • • dbase • fbsql • fdf • ncurses • ming • sybase (-> sybase_ct) • 21 msql Deprecated: ereg
  • 22. PHP 5.4 Released Date 1.Mar.2012 22
  • 23. What‟s New in PHP 5.4 • Memory and Performance Improvements • JsonSerializable Interface • Binary Notation • Traits • Improved Error Messages • Short Array Syntax • Array to String Conversion Notice • Function Array De-referencing • Short open tag • Instance Method Call • Upload progress • Closure Binding • Removed Features • Objects as Functions • Other Changes and Features • Built-in Web Server (CLI) 23
  • 24. Memory and Performance Improvements 24
  • 25. Memory and Performance Improvements 25
  • 26. Memory and Performance Improvements 26
  • 27. Traits Traits is like compiler-assisted copy-and-paste. Traits has an extended interface mechanism that allows the interface to contain an actual implementation of its methods. Example: trait Singleton { } public static function getInstance() { ... } // Singleton method is now available for } both classes A::getInstance(); class A { B::getInstance(); use Singleton; // ... } 27 class B extends ArrayObject { use Singleton; // ...
  • 28. Traits Example: trait Hello { public function sayHello() { echo 'Hello '; } } trait World { public function sayWorld() { echo 'World!'; } } trait HelloWorld { use Hello, World; } 28 class MyHelloWorld { use HelloWorld; } $o = new MyHelloWorld(); $o->sayHello(); $o->sayWorld(); //Output: 'Hello World!
  • 29. Short Array Syntax A simple, but very popular syntax addition. That is, you now no longer need to use the „array‟ keyword to define an array. Example: $a = [1, 2, 3]; $b = ['foo' => 'orange', 'bar' => 'apple']; var_dump( array('foo', 'foo' => 'bar') == ['foo', 'foo' => 'bar'] ); //output: true 29
  • 30. Function Array De-referencing Another oft-requested syntax addition. Function calls that return an array can now be de-referenced directly: Example: function fruits() { return ['apple', 'banana', 'orange']; } echo fruits()[0]; // Outputs: apple 30
  • 31. Instance Method Call Related to function array dereferencing, you can now call a method on object instantiation. And as in previous versions, you can of course still chain method calls, so you can now write code like this: Example: class foo { public $x = 1; public function getX() { return $this->x; } public function setX($val) { $this->x = $val; return $this; } } $X = (new foo)->setX(20)->getX(); echo $X; // 20 31
  • 32. Instance Method Call Although, unless your constructor is doing something useful, since the instantiated object is thrown away perhaps you should be using a static method call here instead. If we combine it with the short array syntax and function array de-referencing we can write some really convoluted code: class foo extends ArrayObject { public function __construct($arr) { parent::__construct($arr); } } echo (new foo( [1, [4, 5], 3] ))[1][0]; What is output? 32
  • 33. Closure Binding Although closure is introduced in 5.3 but binding option include in 5.4 where they interact with objects. Example: class Foo { private $prop; function __construct($prop) { $this->prop = $prop; } public function getPrinter() { return function() { echo ucfirst($this>prop); }; } } 33 $a = new Foo('bar'); $b = new Foo('pickle'); $func = $a->getPrinter(); $func(); // Outputs: Bar $func = $func->bindTo($b); $func(); // Outputs: Pickle
  • 34. Objects as Functions There is a new magic method called “__invoke” which can be used like this: Example: class MoneyObject { private $value; function __construct($val) { $this->value = $val; } function __invoke() { return sprintf('$%.2f',$this->value); } } $Money = new MoneyObject(11.02/5*13); echo $Money(); // Outputs: $28.65 34
  • 35. Built-in Web Server (CLI) The CLI server is a tiny Web server implementation that you can run from the command line. This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network. % php -S localhost:8080 /path/to/router.php PHP 5.4.0 Development Server started at Sun Mar 11 13:28:01 2012 Listening on localhost:8080 Document root is /tmp/web Press Ctrl-C to quit. 35
  • 36. JsonSerializable Interface You can now control what happens if someone tries to json_encode() your object by implementing the JsonSerializable interface: Example: class Foo implements JsonSerializable { private $data = 'Bar'; public function jsonSerialize() { return array('data'=>$this->data); } } echo json_encode(new Foo); // Outputs: {"data":"Bar"} 36
  • 37. Binary Notation To go along with PHP‟s native support for hexadecimal and octal there is now also binary notation: $mask = 0b010101; 37
  • 38. Improved Error Messages Error messages are slightly improved. Before: % php -r 'class abc foo' Parse error: syntax error, unexpected T_STRING, expecting '{' in Command line code on line 1 After: % php -r 'class abc foo' Parse error: syntax error, unexpected 'foo' (T_STRING), expecting '{' in Command line code on line 38
  • 39. Array to String Conversion Notice If you have ever used PHP you have probably ended up with the word “Array” randomly appearing in your page because you tried to output an array directly. Whenever an array is directly converted to a string, chances are it is a bug and there is now a notice for that: Example: $a = [1,2,3]; echo $a; //Output notice: Note: Array to string conversion in example.php onlLine 2 39
  • 40. Short open tag <?= is now always available, regardless of the short_open_tag php.ini option 40
  • 41. Upload progress When the session.upload_progress.enabled INI option is enabled, PHP will be able to track the upload progress of individual files being uploaded. This information isn't particularly useful for the actual upload request itself, but during the file upload an application can send a POST request to a separate endpoint to check the status. The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. Example: 41 <?php $key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progr ess.name")]; var_dump($_SESSION[$key]); ?>
  • 42. Upload progress <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" /> <input type="file" name="file1" /> <input type="file" name="file2" /> <input type="submit" /> </form> t/> field // The following 3 elements equals those in $_FI LES "name" => "foo.avi", "tmp_name" => "/tmp/phpxxxxxx", "error" => 0, "done" => true, // True when the POST handler has finished handling this file "start_time" => 1234567890, // When this file has started to be processed "bytes_processed" => 57343250, // Number of b ytes received and processed for this file The data stored in the session will look like this: ), // An other file, not finished uploading, in the sam e request <?php 1 => array( $_SESSION["upload_progress_123"] = array( "field_name" => "file2", "start_time" => 1234567890, // The request time "name" => "bar.avi", "content_length" => 57343257, // POST content l "tmp_name" => NULL, ength "error" => 0, "bytes_processed" => 453489, // Amount of byte "done" => false, s received and processed "start_time" => 1234567899, "done" => false, // true when the POST h "bytes_processed" => 54554, andler has finished, successfully or not ), "files" => array( ) 0 => array( ); "field_name" => "file1", // Name of the <inpu 42
  • 43. Removed Features Safe Mode • Not really “safe” and caused many problems Magic Quotes • Poor mechanism for securing SQL data Extension: sqlite - Note that ext/sqlite3 and ext/pdo_sqlite are not affected Functions: define_syslog_variables import_request_variables session_is_registered session_register session_unregister mysqli_bind_param mysqli_bind_result mysqli_fetch 43
  • 44. Other Changes and Features Session status: We can check session status using session_status() which returns the CURRENT status of the session, whether sessions are disabled, if there is an active session, or if there are no active sessions. Example: //If sessions are disabled //would return PHP_SESSION_DISABLED (0) echo session_status(); // echo PHP_SESSION_NONE (1) session_start(); echo session_status(); // echo PHP_SESSION_ACTIVE (2) session_destroy(); echo session_status(); // echo PHP_SESSION_NONE (1) SessionHandler is a class help make building custom session handlers easier. The SessionHandler class implements the SessionHandlerInterface, which may be independently called in by a custom class. SessionHandler methods include: • close() – executed on the close of the session • destroy() – executed when destroying a session • gc() – cleans up expired sessions • open() – when opening or creating a session • read() – executed after session_start() • write() – executed by session_write_close() 44
  • 45. PHP 5.5 Release date 20-Jun-2013 45
  • 46. What‟s New in PHP 5.5 • • finally keyword • New password hashing API • foreach now supports list() • empty() supports arbitrary expressions • array and string literal dereferencing • Array_column • Class name resolution via ::class • OPcache extension added • Improvements to GD • 46 Generators Datetime
  • 47. Generators Support for generators has been added via the yield keyword. Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface. Example: function xrange($start, $limit, $step = 1) { for ($i = $start; $i <= $limit; $i += $step) { yield $i; } } echo 'Single digit odd numbers: '; /* * Note that an array is never created or returned, * which saves memory. */ foreach (xrange(1, 9, 2) as $number) { echo "$number "; } echo "n"; 47
  • 48. finally keyword Try-catch blocks now support a finally block for code that should be run regardless of whether an exception has been thrown or not. Example: Problem: $db = mysqli_connect(); try { call_some_function($db); //function may throw exceptions which we can „t handle } catch (Exception $e) { mysqli_close($db); throw $e; } mysql_close($db); 48 Solution: $db = mysqli_connect(); try { call_some_function($db);//function may throw exceptions which we can „t handle } finally { mysqli_close($db); }
  • 49. New password hashing API A new password hashing API that makes it easier to securely hash and manage passwords using the same underlying library as crypt() in PHP has been added. string password_hash ( string $password , integer $algo [, array $options ] ) Example: echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."n"; Output: $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a Using CRYPT_BLOWFISH algo and $2y$ identifier by default and default cost of 10 $options = [ 'cost' => 12, ]; echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."n"; Output: $2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K 49
  • 50. foreach now supports list() he foreach control structure now supports unpacking nested arrays into separate variables via the list() construct. Example: <?php $array = [ [1, 2], [3, 4], ]; foreach ($array as list($a, $b)) { echo "A: $a; B: $bn"; } ?> Output: A: 1; B: 2 A: 3; B: 4 50
  • 51. empty() supports arbitrary expressions Passing an arbitrary expression instead of a variable to empty() is now supported Example: <?php function always_false() { return false; } if (empty(always_false())) { echo "This will be printed.n"; } if (empty(true)) { echo "This will not be printed.n"; } ?> Output ? 51
  • 52. array and string literal dereferencing Array and string literals can now be dereference directly to access individual elements and characters: Example: <?php echo 'Array dereferencing: '; echo [1, 2, 3][0]; echo "n"; echo 'String dereferencing: '; echo 'PHP'[0]; echo "n"; ?> Output: Array dereferencing: 1 String dereferencing: P 52
  • 53. Array_column Array array_column ( array $array , mixed $column_key [, mixed $index_k ey = null ] ) array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array. 53 $records = array( array( Example: 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe', ), array( 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith', ), array( 'id' => 5342, 'first_name' => 'Jane', ) ); $first_names = array_column($records, 'first_na me'); print_r($first_names); //output Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter ) $last_names = array_column($records, 'last_na me', 'id'); print_r($last_names); //output Array ( [2135] => Doe [3245] => Smith [5342] => Jones [5623] => Doe )
  • 54. Class name resolution via ::class It is possible to use ClassName::class to get a fully qualified name of class ClassName. Example: namespace NameSpace; class ClassName {} echo ClassName::class; echo "n"; Output NameSpaceClassName 54
  • 55. OPcache extension added The Zend Optimiser+ opcode cache has been added to PHP as the new OPcache extension. OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request. 55
  • 56. Improvements to GD Various improvements have been made to the GD extension, these include:  Flipping support using the new imageflip() function.  Advanced cropping support using the imagecrop() & imagecropauto() functions.  WebP read and write support using imagecreatefromwebp() & imagewebp() respectively. 56
  • 57. Datetime DateTime $dt = new DateTime(„2013-05-21‟); $dt2 = $dt->modify(„+1 day‟); echo $dt->format(„Y-m-d‟); //2013-5-22 echo $dt2->format(„Y-m-d‟); //2013-5-22 57
  • 58. Removed/changed • • Case insensitivity no longer locale specific • Logo functions removed: php_logo_guid(), php_egg_logo_guid() etc • 58 No Windows XP or 2003 support Changes to pack() and unpack()
  • 59. Just a few things remaining Tired? 59
  • 60. PSR PHP Standards Recommendation 60
  • 61. PSR‟s PSR-0: Autoloader Standard PSR-1: Basic Coding Standard PSR-2: Coding Style Guide PSR-3: Logger Interface 61
  • 62. Flexigrid Why? 62
  • 63. Flexigrid Flexigrid is a grid viewer, a Jquery Plugin can fetch data using XML/JSON. It can be used for following purpose • • • • • • 63 To fetch data with JSON/XML To give option for show/hide any column To give search box along with grid Easy to customization Easy to go to any page Have button and action function
  • 64. Thank you Question? 64