What you must know about PHP5.4

Source: Internet
Author: User
Tags php cli traits javascript array
PHP5.4.0 significantly improves performance and fixes more than 100 bugs. it abolished register_globals, magic_quotes, and the security mode PHP 5.4. this is another major version upgrade from 5.3. This upgrade is significant. it deletes some irritating functions, resulting in a 20% speed increase and less memory usage.

New features and changes
Key new features of this update include the addition of traits and the simplified Array syntax for the built-in webserver used for testing. The $ this pointer can be used by closures to access instantiated class members,
PHP 5.4.0 significantly improves performance and fixes more than 100 bugs. it abolished register_globals, magic_quotes, and the security mode. It is also worth mentioning that multi-byte support has been enabled by default, default_charset has changed from ISO-8859-1 to UTF-8. by default, "Content-Type: text/html; charset = utf-8" is sent. you no longer need to write meta tags in HTML, or send additional headers for UTF-8 compatibility.

Traits
Traits (horizontal reuse/multi-inheritance) is a set of methods with a structure similar to "class" (but cannot be instantiated). It allows developers to easily reuse methods in different classes. PHP is a single inheritance language, and the subclass can only inherit one parent class, so Traits comes.
The best application of Traits is that multiple classes can share the same functions. For example, to create a website, we need to use Facebook and Twitter's APIs. We need to create two classes. if it is a previous one, we need to write a cURL method and copy/paste it into two classes. No, use Traits to reuse code. this time, we actually followed the DRY (Don't Repeat Yourself) principle.

The code is as follows:


/** 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/'.w.url ));
}
}
/** Facebook API Class */
Class Facebook_API
{
Use cURL; // and here
Public function get ($ url)
{
Return json_decode ($ this-> curl ('http: // graph.facebook.com/'.w.url ));
}
}
$ Facebook = new Facebook_API ();
Echo $ facebook-> get ('20140901')-> name; // Rasmus Lerdorf
/** Now demonstrating the awesomeness of PHP 5.4 syntax */
Echo (new Facebook_API)-> get ('20140901')-> name;
$ Foo = 'get ';
Echo (new Facebook_API)-> $ foo ('20140901')-> name;
Echo (new Twitter_API)-> get ('1/users/show. json? Screen_name = rasmus ')-> name;


Do you understand? No? Let's look at a simpler example.

The code is as follows:


Trait Hello
{
Public function hello ()
{
Return 'hello ';
}
}
Trait Cichui
{
Public function cichui ()
{
Return 'cihui ';
}
}
Class HelloCichui
{
Use Hello, Cichui;
Public function the_end ()
{
Return '! ';
}
}
$ O = new HelloCichui;
Echo $ o-> hello (), $ o-> cichui (), $ o-> the_end ();
Echo (new Hello)-> hello (), (new Cichui)-> cichui (), (new HelloCichui)-> the_end ();


Built-in Web-Sever
In Web development, Apache HTTPD is the best partner of PHP. Sometimes, you do not need to configure httpd for development. conf apache daemon, instead of a super-small Webserver that can be used in the command line. thanks to PHP (thanks to the country first), PHP 5.4 has built CLI Web server. (Php cli webserver is only for development and use, and product usage is declined)

Example ):
Step 1: Create the web root directory, Router, and Index
Create a public_html directory in the root directory of the hard disk (such as disk C), create a new router. php file in the directory, and copy and paste the following code:

The code is as follows:


// 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
}
?>


Create an index. php file and copy and paste the following code:
// Index. php
Echo 'hello cichui.com Readers! ';
?>
Edit your php. ini file, find the "include_path" line, and add c: \ public_html (separated by semicolons ):
110000de_path = ".; C: \ php \ PEAR; C: \ public_html"
Save the disk and exit. check the next step.

Step 2: run Web-Server
Switch to the php installation directory and click the most critical command-run Web-server
Php-S 0.0.0.0: 8080-t C: \ public_html router. php
Have you started? Do not close the window. if the process closes the Web server, it is also closed.
Open the browser: access http: // localhost: 8080/index. php,
Hello cichui.com Readers!
See it? Yes, that's it!
Tip 1:You can consider building a self-built php-server.bat batch processing, after throwing it on the desktop can be double-clicked to start up.
Tip 2:Using 0.0.0.0 instead of localhost ensures that the Internet does not access your web server.

Simplified Array syntax
PHP 5.4 provides you with the simplified array syntax:

The code is as follows:


$ Fruits = array ('append', 'oranges', 'banas'); // "old" way
// Learn the Javascript array
$ Fruits = ['append', 'oranges', 'bananas'];
// Associate an array
$ Array = [
'Foo' => 'bar ',
'Bar' => 'foo'
];


Of course, the old syntax is still valid and we have another option.
Array member access parsing (Array dereferencing *)
No temporary variables are required for processing arrays.
Suppose we need to get the middle name of Fang Bin Xin,
Echo explode ('', 'fang Bin sin') [1]; // Bin

Before PHP 5.4, we need:
$ Tmp = explode ('', 'fang Bin sin ');
Echo $ tmp [1]; // Bin
Now we can play with it like this:
Echo end (explode ('', 'fang Bin Xin '); // Xin
Here is an example of an advanced point:

The code is as follows:


Function foobar ()
{
Return ['foo' => ['bar' => 'hello'];
}
Echo foobar () ['foo'] ['bar']; // Hello


* Porcelain hammer note: Array dereferencing literal translation should be an Array to lift the reference, the effect is not good. In fact, more accurate translation should be: "Support for accessing and parsing the array members returned by the function". for details, see the official explanation of PHP.

$ This in anonymous functions
Now, you can reference an anonymous function (also called closure function) through $ this in the class instance)

The code is as follows:


Class Foo
{
Function hello (){
Echo 'hello Cichui! ';
}
Function anonymous ()
{
Return function (){
$ This-> hello (); // it was impossible to do this 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 Cichui!
In fact, it can also be used in the past, which is a little effort:
Function anonymous ()
{
$ That = $ this; // $ that is now $ this
Return function () use ($ that ){
$ That-> hello ();
};
}


No matter how configured in php. ini, short_open_tag replaces the previous one.

Binary direct quantity supported
Octal (oct), followed by 0; hex, followed by 0x; binary (bin). now you can add 0b to the front.
Echo 0b11111; // PHP 5.4 supports binary
Echo 31; // decimal
Echo 0x1f; // hexadecimal
Echo 037; // octal

Function type prompt
Since PHP 5.1, type prompts support objects and arrays, and PHP 5.4 supports callable.

The code is as follows:


Function my_function (callable $ x)
{
Return $ x ();
}
Function my_callback_function () {return 'Hello Cichui! ';}
Class Hello {static function hi () {return 'Hello Cichui! ';}}
Class Hi {function hello () {return 'Hello Cichui! ';}}
Echo my_function (function () {return 'Hello Cichui! ';}); // Closure 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 name, method name


High precision timer
The $ _ SERVER ['request _ TIME_FLOAT '] array variable is introduced here, with microsecond precision (one second per million, float type ). It is useful for calculating the script running time:
1 echo 'executedin', round (microtime (true)-$ _ SERVER ['request _ TIME_FLOAT '], 2)

Summary
In short, this PHP 5.4 upgrade has made a lot of changes. It is time to upgrade.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.