Home >Backend Development >PHP Tutorial >What you must know about PHP 5.4_PHP Tutorial

What you must know about PHP 5.4_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 14:59:23966browse

PHP 5.4 is here, this is another major version upgrade since 5.3. The changes in this upgrade are more significant, and some outdated functions have been deleted, resulting in speed improvements of up to 20% and less memory usage.

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

Traits
Traits (horizontal reuse/multiple inheritance) are a set of methods that are structured like "classes" (but cannot be instantiated), which allow developers to easily Reuse methods. PHP is a single inheritance language, and subclasses can only inherit one parent class, so here comes Traits.
The best application of Traits is that multiple classes can share the same function. For example, if we want to build a website, we need to use the APIs of Facebook and Twitter. We need to create 2 classes. If it were before, we would need to write a cURL method and copy/paste it into both classes. No need now, use Traits to reuse code, this time truly following the DRY (Don't Repeat Yourself) principle.

Copy code 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/'.$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;
$foo = 'get';
echo (new Facebook_API)->$foo('500058753')- >name;
echo (new Twitter_API)->get('1/users/show.json?screen_name=rasmus')->name;

Do you understand? No? Then take a look at a simpler example
Copy code The code is as follows:

trait Hello
{
public function hello()
{
return 'Hello';
}
}
trait Cichui
{
public function cichui()
{
return ' cichui';
}
}
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 PHP’s best partner. Sometimes, when you develop, you don't need the apache killer that needs to configure httpd.conf, but you only need an ultra-small Webserver that can be used in the command line. Thanks to PHP (thanks to the country in advance), PHP 5.4 has a built-in CLI this time Web server. (PHP CLI webserver is for development use only and not for product use)

For example (windows platform):
Step 1: Establish web root directory, Router and Index
Create a public_html directory in the root directory of the hard disk (such as drive C), create a new router.php file in the directory, and copy and paste the following code into it:
Copy 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 a new index.php file, 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 semicolon):
1include_path = ".;C:phpPEAR;C:public_html"
Save and exit, see the next step

Step 2: Run Web-Server
Switch to the php installation directory and type 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 is closed, the Web server will also be closed.
Open the browser: visit http://localhost:8080/index.php,
Hello cichui.com Readers!
Did you see it? Yes, that’s it!
Tip 1: You can consider building a batch process of php-server.bat yourself, and you can double-click it to start it after throwing it on the desktop.
Tip 2: Use 0.0.0.0 instead of localhost to ensure that the external network will not access your web serve.

Simplified Array syntax
PHP 5.4 provides you with streamlined array syntax:

Copy code Code As follows:

$fruits = array('apples', 'oranges', 'bananas'); // "old" way
// Learn Javascript arrays
$fruits = ['apples', 'oranges', 'bananas'];
// Associative array
$array = [
'foo' => 'bar',
'bar' => ; 'foo'
];

Of course, the old syntax is still valid and we have one more option.
Array dereferencing*)
No temporary variables are needed to process arrays.
Suppose we need to get the middle name of Fang Bin Xin,
echo explode(‘ ‘, ‘Fang Bin Xin')[1]; // Bin

Before PHP 5.4, we needed this:
$tmp = explode(' ', 'Fang Bin Xin');
echo $tmp[1]; // Bin
Now, we can play like this:
echo end(explode(' ', 'Fang Bin Xin')); // Xin
A more advanced example:

Copy code The code is as follows:

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

*Porcelain Hammer Note: The literal translation of Array dereferencing should be array dereferencing, which is not very effective. In fact, a more accurate translation should be: "Support for array member access analysis of function return results", see the official PHP explanation for details.

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

Copy code The code is as follows:

class Foo
{
function hello() {
echo 'Hello Cichui!';
}
function anonymous()
{
return function() {
$this->hello(); // It was impossible to play like 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, I could make do with it before, but it was a bit laborious:
function anonymous()
{
$that = $this; // $that is now $this
return function() use ($ that) {
$that->hello();
};
}

No matter how it is configured in php.ini, short_open_tag will replace the previous one.

Support binary literals
Octal (oct), add 0 in front; hexadecimal (hex), add 0x in front; binary (bin), now add 0b in front.
echo 0b11111; // PHP 5.4 supports binary
echo 31; // Decimal
echo 0x1f; // Hexadecimal
echo 037; // Octal

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

Copy code 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
This time the $_SERVER['REQUEST_TIME_FLOAT'] array variable is introduced, with microsecond-level precision (one millionth of a second, float type). It will be very useful for counting script running time:
1echo 'Executed in ', round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2)

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328139.htmlTechArticlePHP 5.4 is here, which is another major version upgrade since 5.3. The changes in this upgrade are more significant. Some outdated functions have been deleted, resulting in up to 20% speed increase and less memory usage...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn