Date post: | 15-Jan-2015 |
Category: |
Technology |
Upload: | michael-stowe |
View: | 15,742 times |
Download: | 1 times |
PHP 5.4 What’s New and What’s Changed
APRIL 7, 2012
michael stowe
• 10+ years experience hacking PHP
• Developed web applications for large non-profits, the medical field, law
enforcement, and ecommerce websites
• Open Source Contributor (3 WordPress plugins, multiple scripts)
• Software Engineer at CaringBridge.org (half a million visitors every day)
• Zend Certified PHP 5.3 Software Engineer
.com
@mikegstowe
MIKESTOWE
THE MOST IMPORTANT CHANGE
The 3 in 5.3 became a 4! (very important)
BUT WHAT WILL PHP 5.4 BREAK?
Well for starters…
• break and continue no longer accept variable arguments • safe_mode is no longer supported • Salsa10/20 algorithms have been removed • Magic Quotes • (object) null now throws a warning • (string) array() now throws an E_NOTICE • Shadowing SuperGlobals as parameter names now causes fatal error
Reserved Keywords In PHP 5.4, the following keywords are now reserved and cannot be used as function or class names:
• trait
• callable
• insteadof
Bye-Bye Functions In PHP 5.4, the following functions have been removed: • define_syslog_variables
• import_request_variables
• session_is_registered
• session_register
• session_unregister
• mysqli_bind_param
• mysqli_bind_result
• mysqli_fetch
Bye-Bye Extensions In PHP 5.4, the following extension has been removed:
• sqlite
Changed Extensions Other important changes:
• mysqli_result() now implements Traversable
• pdo_mysql no longer supports MySQL < 4.1
• mysqlnd has had named pipes support added
INI Removals Other important changes:
• register_globals and register_long_arrays have been removed!!! • safe_mode and all related components removed • y2k_compliance removed • Zend.ze1_compatibility_mode removed
(it’s about time!)
NOW FOR THE JUICY STUFF
PHP 5.4 INI STUFF PHP 5.4 comes with the following new ini directives:
• cli.pager and cli.prompt for CLI SAPI using readline in interactive mode • zend.multibyte to control new multibyte support (off by default) • session.upload directives • enable_post_data_reading to stop POST data from being read and processed (when disabled) • default_charset is now UTF-8 in distributed php ini files (still defaults to “”).
New Functions Here are some of the brand new functions!
• hex2bin()
• http_response_code()
• get_declared_traits()
• getimagesizefromstring()
• stream_set_chunk_size()
• socket_import_stream()
• trait_exists()
• header_register_callback()
• class_uses()
• session_status()
• session_register_shutdown()
• mysqli_error_list()
• mysqli_stmt_error_list() • and others (Libxml, LDAP, Intl)
New Functions (cont) Here are some of the brand new functions!
New Features in 5.4 And the big ticket items in PHP 5.4 include:
• Binary Notation • Short-hand arrays • Dereferencing arrays • Traits • Class Instantiation Chaining • Session Status and Handler • File Upload Tracking • Built in Web Server
BINARY NOTATION Previously in PHP, you were able to write integers as decimals (10), Octals (012), and Hexadecimals (0xA). Now in PHP 5.4 you can use binary notation for integers by preceding the binary number with “0b” – such as (0b1010).
That‟s zero-lower-case-b followed by the binary.
<?php
// Decimal
echo (string) 10; // 10
// Octal
echo (string) 012; // 10
// Hexadecimal
echo (string) 0xA; // 10
// Binary
echo (string) 0b1010; // 10
?>
Example Usage
That‟s zero-lower-case-b followed by the binary.
Binary is calculated by using the powers of 2.
IE 20, 21, 22, 23, etc.
So 100101 would be equal to: [(1) × 25] + [(0) × 24] + [(0) × 23] + [(1) × 22] + [(0) × 21] +
[(1) × 20]
SHORT-HAND ARRAYS Finally, in PHP you can now use the short bracket syntax for arrays. While really not a huge deal, this aligns PHP with many of the other programming languages, and will probably make switching from another language just a little easier (although array(1,2,3) is pretty simple).
$array = array(1,2,3); $array = [1,2,3];
<?php
$oldArray = array(1,2,3);
echo (string) $oldArray[1]; // 2
$newArray = [1,2,3];
echo (string) $newArray[1]; // 2
$newArray = [1 => 'Apple', 2, 3];
echo (string) $newArray[1]; // Apple
$newArray = ['apple' => 'Orange'];
echo $newArray['apple']; // Orange
?>
Example Usage
You can have values OR key => value pairs!
$array = array(1,2,3); $array = [1,2,3];
DEREFERENCING ARRAYS Another nice feature in regards to arrays is Array Dereferencing, or being able to access an array object directly off of a method or function.
echo functionReturningAnArray()[1];
<?php
function getArray()
{
return array(1,2,3);
// or return [1,2,3]; short syntax ;)
}
// PHP 5.3
echo (string) getArray()[1]; // error
// PHP 5.4
echo (string) getArray()[1]; // 2
?>
Example Usage
echo functionReturningAnArray()[1];
This works for functions and methods
TRAITS The addition of traits provides the flexibility of “extending” multiple classes without having to go through an entire chain (allowing horizontal design). Unlike many languages, PHP Traits can also contain properties, however, if the class contains a property with the same name it will throw an E_STRICT warning IF the class property === the trait property, or a fatal error if the class property !== the trait property.
Traits are interchangeable classes that can be imported into a class through the “use” declaration.
<?php
trait MyTrait
{
public $MyProperty = 'hello';
public function MyMethod()
{
echo 'world';
}
}
class MyClass
{
use MyTrait;
public function DoStuff()
{
echo $this->MyProperty;
echo ' ';
$this->MyMethod();
}
}
(new MyClass())->DoStuff(); // echos out 'hello world'
?>
Example Usage
<?php
class MyClass
{
use MyTrait, YourTrait
// Assuming both traits have
// exampleMethod() this will
// cause a conflict, unless we
// tell it not to...
{
// Alias for MyTrait's method
MyTrait::exampleMethod as example1;
// Use YourTrait instead of MyTrait
YourTrait::exampleMethod insteadof MyTrait;
}
}
$myClass = new MyClass();
// MyTrait::exampleMethod
$myClass->example1();
// YourTrait::exampleMethod
$myClass->exampleMethod();
?>
Using Multiple Traits
To avoid method conflicts, you can create aliases
using as AND tell PHP which trait‟s method to use
insteadof another trait‟s identically named method
We have to use insteadof to
avoid a conflict
as allows us to still access MyTrait’s exampleMethod
<?php
trait MyTrait
{
public function MyMethod()
{
echo 'MyTrait';
}
}
class MyClass
{
use MyTrait;
public function MyMethod()
{
echo 'MyClass';
}
public function DoStuff()
{
$this->MyMethod();
}
}
(new MyClass())->DoStuff(); // echos out 'MyClass'
?>
Class Overrides
We can still access MyTrait::MyMethod by creating an alias
as shown in the last slide
Trait Functions
For more on traits visit: http://php.net/manual/en/language.oop5.traits.php
trait_exists() – similar to class_exists(), this function checks to see if the trait has been defined and returns an boolean. get_declared_traits() – similar to get_declared_classes(), this function returns an array of traits that have been declared.
Traits & the Reflection Class
For more on the ReflectionClass visit: http://php.net/manual/en/class.reflectionclass.php
There have also been several methods added to the ReflectionClass: getTraits() returns an array of all traits used in a class, while getTraitNames() returns an array of the trait names in a class. getTraitAliases() returns an array of aliases linked to its original trait and method. isTrait() returns whether or not a tested object is a trait
CLASS INSTANTIATION CHAINING
As you may have noticed by the Traits code example, PHP 5.4 let’s you chain a class instantiation using parenthesis. This allows you to instantiate a class, and call a method all in one act.
(new ClassName())->classMethod(„param1‟);
<?php
class Test
{
public function hello()
{
echo 'hello world';
}
}
// in PHP 5.3 this would be an error
// in PHP 5.4 it echos 'hello world'
echo (new Test())->hello();
?>
Example Usage
Keep in mind that just because you can do something doesn’t mean you should. Stick to coding standards.
(new ClassName())->classMethod(„param1‟);
SESSIONS
PHP 5.4 introduces four new Session items; session_status(), session_register_shutdown(), SessionHandler, and Session based file upload tracking.
SESSION_STATUS
session_status() returns the CURRENT status of the session, whether sessions are disabled, if there is an active session, or if there are no active sessions.
session_status() allows you to see the session‟s
status in real time instead of checking the SuperGlobal and headers.
Let’s take a look at it in action…
<?php
//If sessions are disabled
//would return PHP_SESSION_DISABLED (0)
echo session_status(); // echos PHP_SESSION_NONE (1)
session_start();
echo session_status(); // echos PHP_SESSION_ACTIVE (2)
session_destroy();
echo session_status(); // echos PHP_SESSION_NONE (1)
?>
Example Usage
session_status() allows you to see the session‟s status in
real time instead of checking the SuperGlobal and headers.
SESSION_REGISTER_SHUTDOWN
session_register_shutdown() registers session_write_close() as a shutdown function.
It‟s important to remember that all the other session_register functions have been deprecated.
<?php
session_start();
session_register_shutdown();
?>
SESSIONHANDLER SessionHandler is a class introduced in PHP 5.4 to help make building custom session handlers easier. The SessionHandler class implements the SessionHandlerInterface, which may be independently called in by a custom class.
An instance of this class, a class that extends it, or a
custom class implementing the SessionHandlerInterface
will be passed to session_set_save_handler()
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()
SESSIONHANDLER
An instance of this class, a class that extends it, or a
custom class implementing the SessionHandlerInterface
will be passed to session_set_save_handler()
<?php
class MyHandler extends SessionHandler
{
public function read($session_id)
{
/** GET SESSION DATA FROM YOUR SOURCE **/
}
public function write($session_id, $session_data)
{
/** WRITE SESSION DATA TO YOUR SOURCE **/
}
}
?>
Example Usage
http://www.php.net/manual/en/class.sessionhandler.php
An instance of this class, a class that extends it, or a
custom class implementing the SessionHandlerInterface
will be passed to session_set_save_handler()
FILE UPLOAD TRACKING File upload tracking allows you to track the progress of a file upload through sessions.
This is done only using PHP and
JavaScript!
File upload tracking is setup through the session.upload_progress ini directives, and then stored in the $_SESSION SuperGlobal
File Upload Tracking INI Directives: • session.upload_progress.enabled
• session.upload_progress.cleanup
• session.upload_progress.prefix
• session.upload_progress.name
• session.upload_progress.freq
• session.upload_progress.min_freq
FILE UPLOAD TRACKING
File upload tracking is setup through the session.upload_progress ini directives, and then stored in the $_SESSION SuperGlobal
FILE UPLOAD TRACKING After setting the appropriate ini directives, you will need to setup your upload form:
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>"
method="POST" id="myForm"
enctype="multipart/form-data">
<input type="hidden" value="myForm"
name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
</form>
You can then access the file upload progress data from the session:
<?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
echo 100; // File has been Completely Uploaded
}
?>
FILE UPLOAD TRACKING
With the previous PHP script we can return the upload progress in a percentage back to the original form via ajax.
Mix in a little CSS to make it look even
better!
See more code and learn how to make the above example at PHP Master: http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/
FILE UPLOAD TRACKING
$ cd ~/public_html
$ php -S localhost:8000
BUILT-IN WEBSERVER PHP 5.4 also comes with a built-in webserver via the command line for convenience
The server is activated using the –S option
Note: the webserver is for development purposes only, and should not be used in production
PHP 5.4.0 Development Server started at Thu Jul 21 10:53:19 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:53:45 2011] ::1:55801 GET /mylogo.jpg - Request read
[Thu Jul 21 10:53:52 2011] ::1:55803 GET /abc.html - Request read
[Thu Jul 21 10:53:52 2011] ::1:55804 GET /favicon.ico - Request read
$ cd ~/public_html
$ php -S localhost:8000 router.php
Example Usage
Note: the webserver is for development purposes only, and should not be used in production
Would return something like
AND I ALMOST FORGOT…
FASTER!
PHP Performance
PHP 5.4
PHP 5.3
0
5
10
15
20
25
bench.php
micro_bench.php
PHP 5.4
PHP 5.3
PHP 5.4
PHP 5.3 0
200
400
600
800
1000
1200
PHP 5.4
PHP 5.3
PHP Performance
PHP 5.4
PHP 5.3 0
2000
4000
6000
8000
blog drupal
zf
PHP 5.4
PHP 5.3
PHP Performance
Want to see something really cool?
3.1.2012 RELEASED
http://php.net/ChangeLog-5.php
To read that tiny text and see all the changes
@mikegstowe