//... 操作符: 表示这是一个可变参数. php5.6及以上的版本可使用: 函数定义的时候变量前使用.
function intSum(int ...$ints){
return array_sum($ints);
}
var_dump(intSum(2,'3.5'));//5
//严格模式
//模式声明:declare(strict_types=1); 默认情况值为0,值为1代表为严格校验的模式
declare(strict_types=1);
function add(int $a,int $b){
return $a+$b;
}
var_dump(add(2,'3.5')); //Fatal error: Uncaught TypeError: Argument 2 passed to add() must be of the type integer
//有效的返回类型
declare(strict_types = 1);
function getInt(int $value): int {
return $value;
}
print(getInt(6));//6
//无效返回类型
declare(strict_types = 1);
function getNoInt(int $value): int {
return $value+'2.5';
}
print(getNoInt(6));//Fatal error: Uncaught TypeError: Return value of getNoInt() must be of the type integer
6. 匿名类
允许new class {} 创建一个匿名的对象.
<?php
//php7以前 接口实现
interface User{
public function getDiscount();
}
class VipUser implements User{
//折扣系数
private $discount = 0.6;
public function getDiscount() {
return $this->discount;
}
}
class Goods{
private $price = 200;
private $objectVipUser;
//User接口VipUser类实现
public function getUserData($User){
$this->objectVipUser = $User;
$discount = $this->objectVipUser->getDiscount();
echo "商品价格:".$this->price*$discount;
}
}
$display = new Goods();
//常规实例化接口实现对象
$display ->getUserData(new VipUser);//商品价格:120
<?php
//php7 创建一个匿名的对象
interface User{
public function getDiscount();
}
class Goods{
private $price = 200;
private $objectVipUser;
public function getUserData($User){
$this->objectVipUser = $User;
$discount = $this->objectVipUser->getDiscount();
echo "商品价格:".$this->price*$discount;
}
}
$display = new Goods();
//new匿名对象实现user接口
$display ->getUserData(new class implements User{
private $discount = 0.6;
public function getDiscount() {
return $this->discount;
}
});//商品价格:120
11. use 语句
可以使用单个use语句从相同的命名空间导入类,函数和常量,而不是使用多个use语句.
//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};