《PHP學(xué)習(xí):PHP7.1方括號(hào)數(shù)組符號(hào)多值復(fù)制及指定鍵值賦值用法分析》要點(diǎn):
本文介紹了PHP學(xué)習(xí):PHP7.1方括號(hào)數(shù)組符號(hào)多值復(fù)制及指定鍵值賦值用法分析,希望對(duì)您有用。如果有疑問,可以聯(lián)系我們。
PHP實(shí)例本文實(shí)例講述了PHP7.1方括號(hào)數(shù)組符號(hào)多值復(fù)制及指定鍵值賦值用法.分享給大家供大家參考,具體如下:
PHP實(shí)例PHPer 們可能都知道 list 的用法,簡(jiǎn)單來說就是可以在一個(gè)表達(dá)試?yán)锿ㄟ^數(shù)組對(duì)多個(gè)變量賦值:
PHP實(shí)例
$values = array('value1', 'value2');
$list($v1, $v2) = $values;
PHP實(shí)例感覺是不是很方便呢?在 PHP 7.1 中,還能更省事兒:
PHP實(shí)例
[$v1, $v2] = ['foo', 'bar'];
PHP實(shí)例這還不是最給力的,在 PHP 7.1 里我們還可以指定鍵值來賦值,從而不用關(guān)心數(shù)組元素的順序:
PHP實(shí)例
list('v1' => $value1, 'v2' => $value2) = array('v1' => 'foo', 'v2' => 'bar', ...);
// or
['v1' => $value1, 'v2' => $value2] = ['v1' => 'foo', 'v2' => 'bar', ...];
PHP實(shí)例其實(shí)在 PHP 5 的年代,list 就有一個(gè)很不錯(cuò)的用法可能大家都不熟悉:
PHP實(shí)例
$arr = [
['x', 'y'],
['x1', 'y2'],
];
foreach ($arr as list($x, $y)) {
echo $x, ' ', $y, PHP_EOL;
}
PHP實(shí)例到了 PHP 7.1,因?yàn)榭梢灾付ㄦI值賦值,這種用法將更加的靈活,估計(jì)也更加常用:
PHP實(shí)例
$arr = [
['x' => 1, 'y' => '2'],
['x' => 2, 'y' => '4'],
];
foreach ($arr as ['x' => $x, 'y' => $y)) {
echo $x, ' ', $y, PHP_EOL;
}
PHP實(shí)例再看看一個(gè)官網(wǎng)的例子,是不是感覺好像春風(fēng)拂面一樣清爽:
PHP實(shí)例
class ElePHPant
{
private $name, $colour, $age, $cuteness;
public function __construct(array $attributes) {
// $this->name = $attributes['name']; // 以前
// 現(xiàn)在
[
"name" => $this->name,
"colour" => $this->colour,
"age" => $this->age,
"cuteness" => $this->cuteness
] = $attributes;
}
// ...
}
PHP實(shí)例值得一提的是:此種賦值方式,是可以嵌套使用的!
PHP實(shí)例
[[$a, $b], [$c, $d]] = [[1, 2], [3, 4]];
PHP實(shí)例最后,在 PHP 7.1 的提案里有一個(gè)展望,也非常值得期待:
PHP實(shí)例
class ElePHPant
{
private $name, $colour, $age, $cuteness;
public function __construct(["name" => string $name, "colour" => \Colour $colour, "age" => int $age, "cuteness" => float $cuteness]) {
$this->name = $name;
$this->colour = $colour;
$this->age = $age;
$this->cuteness = $cuteness;
}
// ...
}
PHP實(shí)例如果 PHP 推出此語法,那么參數(shù)列表將不再關(guān)心參數(shù)順序,PHP 的小伙伴將不再羨慕 Ruby 的小伙伴啦!
PHP實(shí)例更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
PHP實(shí)例希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助.
轉(zhuǎn)載請(qǐng)注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/3204.html