1. 程式人生 > >php的語法糖

php的語法糖

php的語法糖

php的語法糖

  1. php 三元運算簡寫
最低版本:php 5.3
作用:($value ?: 'No value set.')  ===  ($value ? $value : 'No value set.')
例項:
<?php
    $value = '1';
    var_dump($value ?: 'No value set.');
    //output : string(1) "1"
  1. 可變數量的引數列表
最低版本:php 5.6
作用:PHP 在使用者自定義函式中支援可變數量的引數列表。
例項:
<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
//output : 10
拓展:在 PHP 5.5 及更早版本中,使用函式 func_num_args(),func_get_arg(),和 func_get_args() 。
例項:
<?php
function foo()
{
    $numargs = func_num_args
(); echo "Number of arguments: $numargs<br />\n"; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg(1) . "<br />\n"; } $arg_list = func_get_args(); for ($i = 0; $i < $numargs; $i++) { echo "Argument $i is: " . $arg_list[$i] . "<br />\n"
; } } foo(1, 2, 3); //output: // Number of arguments: 3 // Second argument is: 2 // Argument 0 is: 1 // Argument 1 is: 2 // Argument 2 is: 3