`
haohappy2
  • 浏览: 327646 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

php5.4 New Features

    博客分类:
  • web
 
阅读更多

New Features and Improvements
Some of the key new features include traits, a shortened array syntax, a built-in webserver for testing purposes, use of $this in closures, class member access on instantiation, <?= is always available, and more!

PHP 5.4.0 significantly improves performance, memory footprint and fixes over 100 bugs. Notable deprecated/removed features include register_globals, magic_quotes (about time) and safe_mode. Also worth mentioning is the fact that multibyte support is enabled by default and default_charset has been changed from ISO-8859-1 to UTF-8.

Content-Type: text/html; charset=utf-8 

 is always sent; so there’s no need to set that HTML meta tag, or send additional headers for UTF-8 compatibility.

--------------------------------------------------------------------------------

Traits

The best demonstration of traits is when multiple classes share the same functionality.
Traits (horizontal reuse/multiple inheritance) are a set of methods, which are structurally similar to a class (but can’t be instantiated), that can enable developers to reuse sets of methods freely in several independent classes. Because PHP is a single inheritance language, a subclass can inherit from only one superclass; that’s where traits come to play.

The best use of traits is demonstrated when multiple classes share the same functionality. For instance, imagine that we are building some website, and need to use both the Facebook and Twitter APIs. We build two classes which, in common, have a cURL wrapper function/method. Instead of performing the classic copy & paste of that method – to be used in two classes – we use Traits (copy & paste, compiler style). This way, we make reusable code, and follow the DRY (Don’t Repeat Yourself) principle.

Here’s an example:

/** cURL wrapper trait */
trait cURL {     
 public function curl($url)     {         
  $ch = curl_init();         
  curl_setopt($ch, CURLOPT_URL, $url);         
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);         
  $output = curl_exec($ch);         
  curl_close($ch);         
  return $output;     
 } 
}   
/** Twitter API Class */
class Twitter_API {     
 use cURL; // use trait here     
 public function get($url)     {         
  return json_decode($this->curl('http://api.twitter.com/'.$url));     
 } 
}   
/** Facebook API Class */
class Facebook_API {     
 use cURL; // and here     
 public function get($url)     {         
  return json_decode($this->curl('http://graph.facebook.com/'.$url));     
 } 
}   
$facebook = new Facebook_API(); 
echo $facebook->get('500058753')->name; // Rasmus Lerdorf   
/** Now demonstrating the awesomeness of PHP 5.4 syntax */
echo (new Facebook_API)->get('500058753')->name; // Rasmus Lerdorf 
$foo = 'get'; 
echo (new Facebook_API)->$foo('500058753')->name; // and again, Rasmus Lerdorf 
echo (new Twitter_API)->get('1/users/show.json?screen_name=rasmus')->name; // and yet again, Rasmus Lerdorf 
// P.S. I'm not obsessed with Rasmus :) 

Got it? No? Here is the simplest example! 

trait Net {     
 public function net()     {         
  return 'Net';     
 } 
}   
trait Tuts {     
 public function tuts()     {         
  return 'Tuts';     
 } 
}   
class NetTuts {     
 use Net, Tuts;     
 public function plus()     {         
  return '+';     
 } 
}   
$o = new NetTuts; 
echo $o->net(), $o->tuts(), $o->plus(); 
echo (new NetTuts)->net(), (new NetTuts)->tuts(), (new NetTuts)->plus(); 

 

If you have any question about traits, please post a note in the comments section below.

Important Tip: The magic constant for traits is __TRAIT__.

--------------------------------------------------------------------------------

Built-in CLI Web-Server

In web development, PHP’s best friend is Apache HTTPD Server. Sometimes, though, it can be overkill to set up httpd.conf just to use it within a development environment, when you really need tiny web server that can be launched with a simple command line. Thankfully, PHP 5,4 comes with a built-in CLI web server.

The PHP CLI web server is designed for developmental purposes only, and should not be used in production.
Note: The instructions below are for a Windows environment.

Step 1 – Create Document Root Directory, Router File and Index File

Go to your hard drive root (assuming C:\). Create a directory/folder, called public_html. Create a new file within this folder, and name it router.php. Copy the contents below, and paste it into this newly created file.

<?php 
 // router.php 
if (preg_match('#\.php$#', $_SERVER['REQUEST_URI'])) {     
 require basename($_SERVER['REQUEST_URI']); // serve php file 
} else if (strpos($_SERVER['REQUEST_URI'], '.') !== false) {     
 return false; // serve file as-is 
} ?> 

 

Now, create another file, called index.php. Copy the contents below and save the file.

<?php // index.php 
 echo 'Hello Nettuts+ Readers!'; 
?> 

 

Open your php.ini file (it is located in the PHP install directory – e.g. C:\php).

Find the include_path settings (it is located at ~ th line). Add C:\public_html to the end of the string between quotes, separate by a semicolon. The final result should look like:

include_path = ".;C:\php\PEAR;C:\public_html"

Save and close the file. On to next step.

Step 2 – Run Web-Server

Open the command prompt (Windows + R, type in cmd, hit Enter); you should see something like this, depending on your Windows version.

Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\nettuts>

Change your current directory to the PHP installation by following the example below:

C:\Documents and Settings\nettuts>cd C:\php C:\php>

Here comes the most important part – running the web-server. Copy…

php -S 0.0.0.0:8080 -t C:\public_html router.php

and paste it in the command prompt (right mouse button, click Paste to paste). Hit Enter. If all goes well, you should see something similar to what’s shown below. Do not close the command prompt; if you do, you will exit the web-server as well.


C:\php>php -S 0.0.0.0:8080 -t C:\public_html router.php PHP 5.4.0 Development Server started at Fri Mar 02 09:36:40 2012 Listening on 0.0.0.0:8080 Document root is C:\public_html Press Ctrl-C to quit.

Open up http://localhost:8080/index.php in your browser and you should see:

Hello Nettuts+ Readers!

Voila! That’s it, happy coding!

Tip 1: Make a php-server.bat file with the following contents: C:\php\php -S 0.0.0.0:8080 -t C:\public_html router.php. Double click it, and, now, the server is up and running!

Tip 2: Use 0.0.0.0 instead of localhost if you anticipate that your server will be accessed from the internet.


--------------------------------------------------------------------------------

Shorter Array Syntax

PHP 5.4 offers a new shorter array syntax:

$fruits = array('apples', 'oranges', 'bananas'); // "old" way   
// The same as Javascript's literal array notation 
$fruits = ['apples', 'oranges', 'bananas'];   
// associative array 
$array = [
   'foo' => 'bar',     
   'bar' => 'foo'
]; 

 

Please note that “old” method is still in use and always will be. This is simply an alternative.


--------------------------------------------------------------------------------

Array Dereferencing

No more temporary variables when dealing with arrays!

Let’s imagine that we want to retrieve the middle name of Alan Mathison Turing:

echo explode(' ', 'Alan Mathison Turing')[1]; // Mathison

Sweet; but it wasn’t always this easy. Before 5.4, we had to do:

$tmp = explode(' ', 'Alan Mathison Turing'); echo $tmp[1]; // Mathison

Now, what if we want to get the last name (last element in array):

echo end(explode(' ', 'Alan Mathison Turing')); // Turing

This works fine, however, it will throw a E_STRICT (Strict Standards: Only variables should be passed by reference) error, since it became part of E_ALL in error_reporting.

Here’s a slightly more advanced example:

function foobar() {     
 return ['foo' => ['bar' => 'Hello']]; 
} 
echo foobar()['foo']['bar']; // Hello 

 


--------------------------------------------------------------------------------

$this In Anonymous Functions

 
You can now refer to the object instance from anonymous functions (also known as closures) by using $this.

class Foo {     
 function hello() {         
  echo 'Hello Nettuts!';     
 }       
 function anonymous()  {         
  return function() {             
   $this->hello(); // $this wasn't possible before         
  };     
 } 
}   
class Bar {     
 function __construct(Foo $o) // object of class Foo typehint     {         
  $x = $o->anonymous(); // get Foo::hello()         
  $x(); // execute Foo::hello()     
 } 
} 
new Bar(new Foo); // Hello Nettuts! 

Note that this could be achieved prior to 5.4, but it was overkill.

function anonymous() {     
 $that = $this; // $that is now $this     
 return function() 
 use ($that) {         
  $that->hello();     
 }; 
} 

 


--------------------------------------------------------------------------------

<?= is Always On

Regardless of the php.ini setting, short_open_tag, <?= (open PHP tag and echo) will always be available. This means that you can now safely use:

<?=$title?>

…in your templates instead of…

<?php echo $title ?>


--------------------------------------------------------------------------------

Binary Number Representation

 There are only 0b10 kinds of people;
those who understand binary and those who don’t.
From now on, integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +). To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation, precede the number with 0x. To use binary notation, precede the number with 0b.

Example: representation of number 31 (decimal).

echo 0b11111; // binary, introduced in PHP 5.4 
echo 31; // duh 
echo 0x1f; // hexadecimal 
echo 037; // octal 

 


--------------------------------------------------------------------------------

Callable Typehint

 
Typehinting is for those who desire to make PHP a stronger typed language. Type Hints can only be of the object and array type since PHP 5.1, and callable since PHP 5.4. Traditional type hinting with int and string isn’t yet supported.

function my_function(callable $x) {     
 return $x(); 
}   
function my_callback_function(){
 return 'Hello Nettuts!';
}   
class Hello{
 static function hi(){
  return 'Hello Nettuts!';
 }
} 
class Hi{
 function hello(){
  return 'Hello Nettuts!';
 }
}   
echo my_function(function(){
 return 'Hello Nettuts!';
}); // anonymous 
function echo my_function('my_callback_function'); // callback 
function echo my_function(['Hello', 'hi']); // class name, static method 
echo my_function([(new Hi), 'hello']); // class object, method name 

 


--------------------------------------------------------------------------------

Initialized High Precision Timer

$_SERVER['REQUEST_TIME_FLOAT'] has been added, with microsecond precision (float). This is useful when you need to calculate the execution time for a script.

echo 'Executed in ', round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2), 's'; 

 


--------------------------------------------------------------------------------

__destruct() (or Summary)

Overall, PHP 5.4 offers numerous improvements. Now, it’s up to you to grab a fresh copy from php.net, and make quality Object-Oriented PHP code!

What do you think PHP 5.5 will bring us, and what do you expect?

http://net.tutsplus.com/tutorials/php

 

分享到:
评论

相关推荐

    PHP5.4 64位

    【PHP5.4 64位】是针对Windows Server 8、Windows 8及Windows 7操作系统优化的64位版本的PHP环境。这个版本特别强调了与64位架构的兼容性和对CPU性能的优化,确保在这些系统上运行时能够提供更好的效率和稳定性。在...

    php5.4_memcache.dll 64位

    标题 "php5.4_memcache.dll 64位" 指的是针对PHP 5.4版本的一个64位扩展,用于支持Memcache缓存系统。这个扩展使得PHP应用程序能够利用Memcache服务来存储和检索数据,从而提高网站性能,减少数据库负载。 描述中的...

    php5.4's zenddebugger

    最新的php5.4 zenddebugger.so

    ecshop 完美兼容php5.4以上版本 php5.4 php5.5 php 5..6

    标题提到的“ecshop 完美兼容php5.4以上版本 php5.5 php5.6”意味着这个程序经过优化,能够在PHP 5.4及其后续版本上稳定运行,解决了早期ECShop 2.7.3版本与这些PHP版本的兼容性问题。 描述中指出,ECShop 2.7.3在...

    php5.4.*ts版 php_phpredis.dll

    标题中的“php5.4.*ts版 php_phpredis.dll”指的是在PHP 5.4版本的一个线程安全(TS)构建中使用的扩展模块——php_phpredis.dll。这个扩展是专门为PHP设计的,允许PHP应用程序与Redis内存数据存储进行通信。Redis是...

    php环境5.4一键安装包

    《PHP环境5.4一键安装包详解》 在IT领域,PHP是一种广泛使用的开源脚本语言,尤其在Web开发中占据重要地位。PHP 5.4版本是PHP发展中的一个重要里程碑,它带来了许多新特性与优化,使得开发更加高效便捷。而"php环境...

    php 5.4 安装文件

    **PHP 5.4 安装与配置指南** PHP(Hypertext Preprocessor)是一种广泛使用的开源脚本语言,尤其适用于Web开发。PHP 5.4是该语言的一个重要版本,引入了许多新特性,增强了性能并优化了开发体验。本文将详细介绍...

    php5.4中文手册

    《PHP5.4中文手册》是一份专门为程序员和开发者编写的指南,旨在帮助他们理解和运用PHP5.4这一版本的编程语言。这份手册是中文版,对于中文使用者来说,提供了极大的便利,使得学习和查阅PHP5.4的相关资料变得更加...

    ecshop(php5.4修订版)

    ECShop是一款基于PHP5.4开发的开源电子商务系统,专为中小企业设计,提供了一套完整的网上商店解决方案。在"ecshop(php5.4修订版)"中,我们重点关注的是其针对PHP5.4版本的优化和调整,这使得ECShop在该版本的PHP...

    php5.3-php5.4mongo扩展

    《PHP 5.3到5.4版本Mongo扩展详解及安装指南》 MongoDB是一款流行的开源、高性能、无模式的文档型数据库,广泛应用于大数据处理和分布式存储。PHP作为常用的服务器端脚本语言,与MongoDB的结合为开发者提供了强大的...

    PHP5.4源码包

    **PHP5.4源码包详解** PHP(PHP:Hypertext Preprocessor)是一种广泛使用的开源脚本语言,尤其适用于Web开发,可嵌入到HTML中。PHP5.4是PHP发展过程中的一个重要版本,引入了许多新特性,优化了性能,并修复了大量...

    Apache+php5.4和IIS+php5.4环境下安装imagick

    **Apache+PHP5.4与IIS+PHP5.4环境下安装ImageMagick** ImageMagick是一款强大的开源图像处理库,它可以处理各种图像格式,包括创建、编辑、合成图像等。在Web服务器环境下,结合PHP5.4使用,可以实现动态生成图像、...

    PHP 5.4 使用的 memcache

    **PHP 5.4与Memcache的整合** 在PHP 5.4版本中,开发者可以利用Memcache扩展来实现高效的数据缓存,从而提高Web应用的性能。Memcache是一款广泛使用的分布式内存对象缓存系统,它能存储键值对数据,并在内存中快速...

    PHP5.4redis 扩展文件

    PHP5.4版本的Redis扩展使得开发者能够利用Redis的高效特性,如键值存储、发布/订阅消息队列以及事务处理等功能,来增强Web应用的性能和可扩展性。这个压缩包文件包含了使PHP5.4与Redis服务器通信所需的全部组件。 ...

    php5.4版本 vc9

    PHP 5.4 版本是 PHP 语言的一个重要里程碑,发布于2012年。这个版本引入了许多新特性,优化了性能,并且对Windows环境提供了更好的支持。特别是与VC9(Visual C++ 2008)编译器的结合,使得PHP在Windows平台上运行...

    PHP5.4+php.ini标配.rar

    【PHP5.4详解】 PHP(Hypertext Preprocessor)是一种广泛使用的开源脚本语言,尤其在Web开发领域。PHP5.4是该语言的一个重要版本,它在2012年发布,引入了许多新特性,提升了性能和开发效率。 1. **命名空间...

    PHP5.4最牛逼的中文手册

    《PHP5.4最牛逼的中文手册》是针对PHP5.4版本的一份详尽教程,涵盖了从初学者入门到高级进阶的各种知识点。PHP(Hypertext Preprocessor)是一种广泛使用的开源脚本语言,尤其在Web开发领域中扮演着重要角色。手册的...

    redis php5.4扩展

    4. 测试扩展是否成功加载,可以创建一个简单的PHP脚本,尝试连接到Redis服务器并执行基本操作,如`$redis = new Redis(); $redis-&gt;connect('127.0.0.1', 6379);`。 通过这个扩展,你可以使用PHP的Redis类来执行各种...

    hdwiki_php5.4懒人包

    然而,官方的HDWiki系统并不兼容PHP 5.4及以上版本,这可能会对那些使用较新PHP环境的用户造成困扰。为了应对这个问题,"hdwiki_php5.4懒人包"应运而生。这个资源包经过了特别的修改,使得HDWiki能够在PHP 5.4环境下...

Global site tag (gtag.js) - Google Analytics