Use of short tags
//短标签的使用,echo时使用,一般是是视图模板中使用.以下两种写法相同
$name = '张三';
<?=$name?>
<?php echo $name; ?>
Ternary operator abbreviation added after php5.3
$page = '';
$page = $page ? $page : 1;
echo $page; //1
$page = $page ?: 1;
echo $page; //1
Added after callback php5.3 through anonymous function
//例如数组中每个单元值修改
function test($arr, $callback){
foreach ($arr as $k => $v) {
$arr[$k] = $callback($v);
}
return $arr;
}
$arr = [1,2,3];
$array = test($arr,function ($v){
return $v+1;
});
print_r($array); //[2,3,4]
//Array declaration, use brackets, added after php5.4
$arr = array(1,2,3);
$arr = [1,2,3];
//Function output array, added in php5.4
$arr = array(1,2,3);
$arr = [1,2,3];
//Object direct call
class Dog {
public function bark() {
echo 'ww';
}
}
$dog = new Dog();
$dog->bark(); //ww
(new Dog())->bark(); //ww
The use of trait extraction is actually added after declaring a class php5.5
trait Cat {
public function eat() {
echo '吃';
}
}
trait Bird {
public function fly()
{
echo '飞';
}
}
class SuperMan {
use Cat, Bird;
}
(new SuperMan())->eat();//吃
(new SuperMan())->fly();//飞
//empty function
$a = 3;
echo empty($a-3); //5.5之前会报错,不能判断表达式
//Keyword yield increased after php5.5
//yield不会将单个数据追加到数组,而是没生成一个数据,函数就循环输出一个
function getAll() {
for ($i = 0; $i < 5; $i++) {
yield $i;
}
}
foreach (getAll() as $k => $v) {
echo $v;
}
//Constant definition php5.6const is only used to define class constants, after php5.6 it can be used outside the class, and arrays can be defined
const A = [1,2,3];
echo A[1];//2
//Indefinite parameters will be added after php5.6
function test2 ($a, ...$b) {
print_r($b);
}
test2(1,2,3,4,5); //输出为数组 [2,3,4,5]
//帮函数拆分参数
function test3($a,$b,$c) {
echo $a;
echo $b;
echo $c;
}
$argc = [2,3];
test3(1, ...$argc); //1,2,3
//Ternary operator features are newly added in php7
$page = isset($_GET['page']) ? $_GET['page'] : 1;
echo $page; //1
echo $_GET['page'] ?? 1; //1
//Strong type support, type constraints, the type of parameters passed are constrained, and the type of return value is constrained
function test4(int $a, int $b) :int {
return $a + $b;
}
echo test4(4,7); //如果参数传递的是个字符串,将会直接报错
//The use of anonymous classes
echo (new class{
public $name = '张三';
})->name; //张三