php7新特性的理解和比较

1:null合并运算符(??):如果变量存在且值不为null,它就会返回自身的值,否则返回它的第二个操作数。

//php7以前:if判断
if(empty($_GET['param'])){
	$param = 1;
}else{
	$param = $_GET['param'];
}

//php7以前  三元运算符
$param = empty($_GET['param']) ? 1 : $_GET['param'];//有个问题:如果$_GET['param']的值为null,则会输出1

//php7:null合并运算符
$param = $_GET['param'] ?? 1;//1

2:define()定义常量数组

//php7以前
define("CONTENT", "hello world");
echo CONTENT;//hello world

//PHP7
define('ANIMALS',['dog','cat','bird']);
echo ANIMALS[2];//bird

//PHP7 类外也可使用const来定义常量
const CONSTANT = 'Hello World';
echo CONSTANT;//Hello World

3:组合比较符(<=>):组合比较符用于比较两个表达式,当 a 小 于 、 等 于 或 大 于 a小于、等于或大于 ab时它分别返回-1、0或1. 比较的原则是沿用PHP的常规比较规则进行的。

//整数
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

//浮点数
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

//字符串
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

4:变量类型声明,两种模式:强制(默认)和严格模式. 可以使用下列类型参数: string,int,float,bool

//...运算符表示这是一个可变参数,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

5:返回值类型声明:增加返回类型声明的支持.类似于参数类型声明.(用法在函数定义的后面加 :类型名)

//有效的返回类型
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以前的接口实现
interface User
{
    public function getDiscount();
}

class VipUser implements User
{
    private $discount = 0.6;
    
    public function getDiscount()
    {
        return $this->discount;
    }
}

class Goods
{
    private $price;
    private $vipUser;
    
    public function __construct($price,$vipUser)
    {
        $this->price = $price;
        $this->vipUser = $vipUser;
        
    }
    
    public function getUserData()
    {
        $discount = $this->vipUser->getDiscount();
        echo sprintf('商品价格:%s',$this->price * $discount);
    }
}

$display = new Goods(200,new vipUser());
$display->getUserData();

//php7
interface User
{
    public function getDiscount();
}

class Goods
{
    private $price;
    private $vipUser;
    
    public function __construct($price,$vipUser)
    {
        $this->price = $price;
        $this->vipUser = $vipUser;
        
    }
    
    public function getUserData()
    {
        $discount = $this->vipUser->getDiscount();
        echo sprintf('商品价格:%s',$this->price * $discount);
    }
}

$display = new Goods(200,new class implements User{
    private $discount = 0.6;
    
    public function getDiscount()
    {
        return $this->discount;
    }
});
$display->getUserData();

7:Closure::call():临时绑定一个对象作用域到一个闭包并调用它,与php5的bindTo相比,性能要快的多。

//php7以前
class A
{
    private $attribute = 'hello world';
}

$getClosure = function(){
    return $this->attribute;
};

$getAttribute = $getClosure->bindTo(new A(),'A');
echo $getAttribute();

//php7:
class A
{
    private $attribute = 'hello world';
}

$getClosure = function(){
    return $this->attribute;
};

echo $getClosure->call(new A);

8:use语句:可以使用单个use语句从相同的命名空间导入类、函数和常量,而不是使用多个use语句。

//php7之前
usesome\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};

9:新增intdiv函数,接收两个参数,返回值为第一个参数除以第二个参数的值并取整。

echo intdiv(8,4);//2
echo intdiv(10,4);//2
echo intdiv(5,10);//0

10:php7错误处理:PHP7 改变了大多数错误的报告方式.不同于PHP5的传统错误报告机制,现在大多数错误被作为Error异常抛出.这种Error异常可以像普通异常一样可以被try{}catch块所捕获。如果没有匹配的try / catch块,则调用异常处理函数(由 set_exception_handler() 注册)进行处理.如果尚未注册异常处理函数,则按照传统方式处理:被报告为一个致命错误(Fatal Error).Error类并不是从Exception类扩展出来的,所以用catch (Exception $e) { … } 这样的代码是捕获不到Error的.你可以用 catch (Error $e) { … } 这样的代码,
或者通过注册异常处理函数( set_exception_handler())来捕获Error.
在这里插入图片描述

//php7以前 自定义异常处理
 class getException extends Exception{
     public function errorMsg(){
         return '错误的信息'.$this->getMessage().'<br>错误的代码'.$this->getCode();
     }
 }
 
 try {
    $num =10;
    if($num > 1) {
        throw new getException($num,404);
    }
} catch (getException $e) {
    echo $e->errorMsg();
}

//php7异常处理
try {
    test();
}catch(Error $e) {
    echo $e->getMessage();//Call to undefined function test()
}

11:php7 session选项:php7 以前,我们使用 session 前都是要先代用 session_strat() 函数来初始化的,但这个函数是没有参数可以传的,session 的配置都在 php.ini 文件中。在 php7 后 session_start() 可以接受一个 array 作为参数, 用来覆盖 php.ini 文件中设置的会话配置选项。

session_start([
   'cache_limiter' => 'private', //在读取完毕会话数据之后马上关闭会话存储文件
    'cookie_lifetime'=>3600,   //SessionID在客户端Cookie储存的时间,默认是0,代表浏览器一关闭SessionID就作废
    'read_and_close'=>true   //在读取完会话数据之后, 立即关闭会话存储文件,不做任何修改
]);
$_SESSION['name']='quan';
echo $_SESSION['name'];

12:php4风格的构造函数:在 PHP4 中类中的函数可以与类名同名,这一特性在 PHP7 中被废弃,而且,如果类中没有构造函数时,会产生一个 E_DEPRECATED 错误。

class A {
   function A() {
      print('Style Constructor');
   }
}

$a = new A();
$a->A();//Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; A has a deprecated constructor in /data/574806102 on line 3

class A {
   public function __construct(){}
   function A() {
      print('Style Constructor');
   }
}

$a = new A();
$a->A();//Style Constructor

13:php7不再支持以静态的方式调用非静态方法。

class A {
   function b() {
      print('Non-static call');
   }
}
A::b();//Deprecated: Non-static method A::b() should not be called statically in...
Non-static call

14:php7移除了以下扩展:ereg、mssql、mysql

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值