Вы находитесь на странице: 1из 2

New features - Constant expressions

http://php.net/manual/en/migration56.new-features.php
It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts
where PHP previously expected a static value, such as constant and property declarations and default function
arguments.
<?php
const ONE = 1;
const TWO = ONE * 2;

class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is '.self::THREE;

    public function f($a = ONE + self::THREE) {
        return $a;
    }
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>
The above example will output:
4
The value of THREE is 3

It is also now possible to define a constant array using the const keyword:
<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>
The above example will output:
a

Variadic functions via ...

Variadic functions can now be implemented using the ... operator, instead of relying on func_get_args().

<?php
function f($req, $opt = null, ...$params) {
    // $params is an array containing the remaining arguments.
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>
The above example will output:
$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3
Argument unpacking via ...

Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ...
operator. This is also known as the splat operator in other languages, including Ruby.

<?php
function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>
The above example will output:
6

Exponentiation via **

A right associative ** operator has been added to support exponentiation, along with a **= shorthand
assignment operator.

<?php
printf("2 ** 3 ==      %d\n", 2 ** 3);
printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);

$a = 2;
$a **= 3;
printf("a ==           %d\n", $a);
?>
The above example will output:
2 ** 3 == 8
2 ** 3 ** 2 == 512
a == 8

use function and use const

The use operator has been extended to support importing functions and constants in addition to classes. This is
achieved via the use function and use const constructs, respectively.

<?php
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}

namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;

    echo FOO."\n";
    f();
}
?>
The above example will output:
42
Name\Space\f

Вам также может понравиться