国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7
Home php教程 php手冊(cè) A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7

A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7

Jul 06, 2016 pm 02:24 PM
php php7 Function

A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7

Scalar type declaration

There are two modes: mandatory (default) and strict mode. The following type parameters are now available (either in forced or strict mode): string, int, float, and bool. In the old version, function parameter declarations could only be (Array $arr), (CLassName $obj), etc. Basic types such as Int, String, etc. could not be declared

<&#63;php
function check(int $bool){
var_dump($bool);
}
check(1);
check(true);

If there is no forced type conversion, int(1)bool(true) will be entered. After conversion, bool(true) bool(true)

will be output

Return value type declaration

PHP 7 adds support for return type declarations. The return type declaration specifies the type of the function's return value. The available types are the same as those available in the parameter declaration.

<&#63;php
function arraysSum(array ...$arrays): array
{
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}
print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

The above routine will output:

Array
(
[0] => 6
[1] => 15
[2] => 24
)

null coalescing operator

There are a lot of cases where ternary expressions and isset() are used simultaneously in the project, and the syntactic sugar of null coalescing operator (??) is added. If the variable exists and is not NULL, it returns its own value, otherwise it returns the second operand.

Old version: isset($_GET['id']) ? $_GET[id] : err;

New version: $_GET['id'] ?? 'err';

Spaceship operator (combination comparison operator)

The spaceship operator is used to compare two expressions. When $a is less than, equal to or greater than $b it returns -1, 0 or 1 respectively

<&#63;php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
&#63;>

Define constant array through define()

<&#63;php
define('ANIMALS', ['dog', 'cat', 'bird']);
echo ANIMALS[1]; // outputs "cat"

Anonymous class

Now supports instantiating an anonymous class through new class

<&#63;php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
echo $msg;
}
});
var_dump($app->getLogger());

Unicode codepoint translation syntax

This accepts a Unicode codepoint in hexadecimal form and prints out a UTF-8 encoded string surrounded by double quotes or a heredoc. Any valid codepoint is accepted, and the leading 0 can be omitted.

<&#63;php
echo “\u{9876}”

Old version output: u{9876}

New version input: Like

Closure::call()

Closure::call() now has better performance, a short and concise way to temporarily bind a method to the closure of the object and call it

<&#63;php
class Test{public $name = "lixuan";}
//PHP7和PHP5.6都可以
$getNameFunc = function(){return $this->name;};
$name = $getNameFunc->bindTo(new Test, 'Test');
echo $name();
//PHP7可以,PHP5.6報(bào)錯(cuò)
$getX = function() {return $this->name;};
echo $getX->call(new Test);

Provide filtering for unserialize()

This feature is designed to provide a safer way to unpack unreliable data. It prevents potential code injection through whitelisting.

<&#63;php
//將所有對(duì)象分為_(kāi)_PHP_Incomplete_Class對(duì)象
$data = unserialize($foo, ["allowed_classes" => false]);
//將所有對(duì)象分為_(kāi)_PHP_Incomplete_Class 對(duì)象 除了ClassName1和ClassName2
$data = unserialize($foo, ["allowed_classes" => ["ClassName1", "ClassName2"]);
//默認(rèn)行為,和 unserialize($foo)相同
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

The newly added IntlChar class is designed to expose more ICU functions. This class itself defines many static methods for manipulating unicode characters in multiple character sets. Intl is a Pecl extension and needs to be compiled into PHP before use. You can also apt-get/yum/port install php5-intl

<&#63;php
printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

The above routine will output:

10ffff
COMMERCIAL AT
bool(true)

Expected

The intention is to use backwards and enhance the previous assert() method. It makes enabling assertions cost-effective in production and provides the ability to throw specific exceptions when assertions fail. The old version of the API will continue to be maintained for compatibility purposes, and assert() is now a language construct that allows the first argument to be an expression, not just a string to be calculated or a boolean to be tested.

<&#63;php
ini_set('assert.exception', 1);
class CustomError extends AssertionError {}
assert(false, new CustomError('Some error message'));

The above routine will output:

Fatal error: Uncaught CustomError: Some error message

Group use declarations

Classes, functions and constants imported from the same namespace can now be imported at once with a single use statement.

<&#63;php
//PHP7之前
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// PHP7之后
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
&#63;>

intdiv()

Receives two parameters as dividend and divisor, and returns the integer part of their division result.

<&#63;php
var_dump(intdiv(7, 2));

Output int(3)

CSPRNG

New two functions: random_bytes() and random_int(). Can encrypt and produce protected integers and strings. My poor translation, in short, random numbers have become safe.

random_bytes — Cryptographically protected pseudo-random strings

random_int — cryptographically protected pseudo-random integer

preg_replace_callback_array()

A new function preg_replace_callback_array() has been added. Using this function can make the code more elegant when using the preg_replace_callback() function. Before PHP7, the callback function would be called for every regular expression, and the callback function was contaminated on some branches.

Session options

Now, the session_start() function can receive an array as a parameter, which can override the session configuration items in php.ini.

For example, set cache_limiter to private and close the session immediately after reading the session

<&#63;php
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);

The return value of the generator

The concept of generator is introduced in PHP5.5. Each time the generator function is executed, it gets a value identified by yield. In PHP7, when the generator iteration is completed, the return value of the generator function can be obtained. Obtained through Generator::getReturn().

<&#63;php
function generator() {
yield 1;
yield 2;
yield 3;
return "a";
}
$generatorClass = ("generator")();
foreach ($generatorClass as $val) {
echo $val.” “;
}
echo $generatorClass->getReturn();

The output is: 1 2 3 a

生成器中引入其他生成器

在生成器中可以引入另一個(gè)或幾個(gè)生成器,只需要寫(xiě)yield from functionName1

<&#63;php
function generator1(){
yield 1;
yield 2;
yield from generator2();
yield from generator3();
}
function generator2(){
yield 3;
yield 4;
}
function generator3(){
yield 5;
yield 6;
}
foreach (generator1() as $val){
echo $val, " ";
}

輸出:1 2 3 4 5 6

不兼容性

1、foreach不再改變內(nèi)部數(shù)組指針

在PHP7之前,當(dāng)數(shù)組通過(guò) foreach 迭代時(shí),數(shù)組指針會(huì)移動(dòng)?,F(xiàn)在開(kāi)始,不再如此,見(jiàn)下面代碼。

<&#63;php
$array = [0, 1, 2];
foreach ($array as &$val) {
var_dump(current($array));
}

PHP5輸出:

int(1)
int(2)
bool(false)

PHP7輸出:

int(0)
int(0)
int(0)

2、foreach通過(guò)引用遍歷時(shí),有更好的迭代特性

當(dāng)使用引用遍歷數(shù)組時(shí),現(xiàn)在 foreach 在迭代中能更好的跟蹤變化。例如,在迭代中添加一個(gè)迭代值到數(shù)組中,參考下面的代碼:

<&#63;php
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}

PHP5輸出:

int(0)

PHP7輸出:

int(0)
int(1)

3、十六進(jìn)制字符串不再被認(rèn)為是數(shù)字

含十六進(jìn)制字符串不再被認(rèn)為是數(shù)字

<&#63;php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));

PHP5輸出:

bool(true)
bool(true)
int(15)
string(2) "oo"

PHP7輸出:

bool(false)
bool(false)
int(0)
Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

4、PHP7中被移除的函數(shù)

被移除的函數(shù)列表如下:

call_user_func() 和 call_user_func_array()從PHP 4.1.0開(kāi)始被廢棄。

已廢棄的 mcrypt_generic_end() 函數(shù)已被移除,請(qǐng)使用mcrypt_generic_deinit()代替。

已廢棄的 mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() 和 mcrypt_ofb() 函數(shù)已被移除。

set_magic_quotes_runtime(), 和它的別名 magic_quotes_runtime()已被移除. 它們?cè)赑HP 5.3.0中已經(jīng)被廢棄,并且 在in PHP 5.4.0也由于魔術(shù)引號(hào)的廢棄而失去功能。

已廢棄的 set_socket_blocking() 函數(shù)已被移除,請(qǐng)使用stream_set_blocking()代替。

dl()在 PHP-FPM 不再可用,在 CLI 和 embed SAPIs 中仍可用。

GD庫(kù)中下列函數(shù)被移除:imagepsbbox()、imagepsencodefont()、imagepsextendfont()、imagepsfreefont()、imagepsloadfont()、imagepsslantfont()、imagepstext()

在配置文件php.ini中,always_populate_raw_post_data、asp_tags、xsl.security_prefs被移除了。

5、new 操作符創(chuàng)建的對(duì)象不能以引用方式賦值給變量

new 操作符創(chuàng)建的對(duì)象不能以引用方式賦值給變量

<&#63;php
class C {}
$c =& new C;

PHP5輸出:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

PHP7輸出:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

6、移除了 ASP 和 script PHP 標(biāo)簽

使用類(lèi)似 ASP 的標(biāo)簽,以及 script 標(biāo)簽來(lái)區(qū)分 PHP 代碼的方式被移除。 受到影響的標(biāo)簽有:<% %>、<%= %>、

7、從不匹配的上下文發(fā)起調(diào)用

在不匹配的上下文中以靜態(tài)方式調(diào)用非靜態(tài)方法, 在 PHP 5.6 中已經(jīng)廢棄, 但是在 PHP 7.0 中, 會(huì)導(dǎo)致被調(diào)用方法中未定義 $this 變量,以及此行為已經(jīng)廢棄的警告。

<&#63;php
class A {
public function test() { var_dump($this); }
}
// 注意:并沒(méi)有從類(lèi) A 繼承
class B {
public function callNonStaticMethodOfA() { A::test(); }
}
(new B)->callNonStaticMethodOfA();

PHP5輸出:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

PHP7輸出:

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8
Notice: Undefined variable: this in /tmp/test.php on line 3

NULL

8、在數(shù)值溢出的時(shí)候,內(nèi)部函數(shù)將會(huì)失敗

將浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)的時(shí)候,如果浮點(diǎn)數(shù)值太大,導(dǎo)致無(wú)法以整數(shù)表達(dá)的情況下, 在之前的版本中,內(nèi)部函數(shù)會(huì)直接將整數(shù)截?cái)?,并不?huì)引發(fā)錯(cuò)誤。 在 PHP 7.0 中,如果發(fā)生這種情況,會(huì)引發(fā) E_WARNING 錯(cuò)誤,并且返回 NULL。

9、JSON 擴(kuò)展已經(jīng)被 JSOND 取代

JSON 擴(kuò)展已經(jīng)被 JSOND 擴(kuò)展取代。 對(duì)于數(shù)值的處理,有以下兩點(diǎn)需要注意的: 第一,數(shù)值不能以點(diǎn)號(hào)(.)結(jié)束 (例如,數(shù)值 34. 必須寫(xiě)作 34.0 或 34)。 第二,如果使用科學(xué)計(jì)數(shù)法表示數(shù)值,e 前面必須不是點(diǎn)號(hào)(.) (例如,3.e3 必須寫(xiě)作 3.0e3 或 3e3)

10、INI 文件中 # 注釋格式被移除

在配置文件INI文件中,不再支持以 # 開(kāi)始的注釋行, 請(qǐng)使用 ;(分號(hào))來(lái)表示注釋。 此變更適用于 php.ini 以及用 parse_ini_file() 和 parse_ini_string() 函數(shù)來(lái)處理的文件。

11、$HTTP_RAW_POST_DATA 被移除

不再提供 $HTTP_RAW_POST_DATA 變量。 請(qǐng)使用 php://input 作為替代。

12、yield 變更為右聯(lián)接運(yùn)算符

在使用 yield 關(guān)鍵字的時(shí)候,不再需要括號(hào), 并且它變更為右聯(lián)接操作符,其運(yùn)算符優(yōu)先級(jí)介于 print 和 => 之間。 這可能導(dǎo)致現(xiàn)有代碼的行為發(fā)生改變??梢酝ㄟ^(guò)使用括號(hào)來(lái)消除歧義。

<&#63;php
echo yield -1;
// 在之前版本中會(huì)被解釋為:
echo (yield) - 1;
// 現(xiàn)在,它將被解釋為:
echo yield (-1);
yield $foo or die;
// 在之前版本中會(huì)被解釋為:
yield ($foo or die);
// 現(xiàn)在,它將被解釋為:
(yield $foo) or die;

以上所述是小編給大家介紹的淺析PHP7新功能及語(yǔ)法變化總結(jié),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)幫客之家網(wǎng)站的支持!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

See all articles