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.
/**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
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:
// 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:
$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:
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
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.
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.

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
