php7新特性的理解和比较总结(2)
<?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
7. Closure::call()
Closure::call() 方法被添加为一个简短的方式来临时绑定一个对象作用域到一个闭包并调用它. 与PHP5的bindTo相比.它的性能要快得多.
<?php //php7以前 class A { private $attribute = 'hello world'; } $getClosure = function(){ return $this->attribute; }; $getAttribute = $getClosure->bindTo(new A, 'A');//中间层闭包 echo $getAttribute();//hello world
<?php //PHP7 class A { private $attribute = 'hello world'; } $getClosure = function(){ return $this->attribute; }; echo $getClosure->call(new A);//hello world
8. unserialize()
unserialize()函数:过滤的特性,可以防止非法数据进行代码注入,提供了更安全的反序列化数据
<?php class A{ public $name = 'admin_a'; } class B{ public $name = 'admin_b'; } $objA = new A(); $objB = new B(); $serializedObjA = serialize($objA); $serializedObjB = serialize($objB); //默认行为是接收所有类; 第二个参数可以忽略 $dataA = unserialize($serializedObjA , ["allowed_classes" => true]); var_dump($dataA);//object(A)#3 (1) { ["name"]=> string(7) "admin_a" } //如果allowed_classes设置为false,unserialize会将所有对象转换为__PHP_Incomplete_Class对象 $dataA = unserialize($serializedObjA , ["allowed_classes" => false]); var_dump($dataA);//object(__PHP_Incomplete_Class)#4 (2) { ["__PHP_Incomplete_Class_Name"]=> string(1) "A" ["name"]=> string(7) "admin_a" } //转换所有对象到 __PHP_Incomplete_Class对象,除了对象"B" $dataB = unserialize($serializedObjB , ["allowed_classes" => ["B"]]); var_dump($dataB);//object(B)#3 (1) { ["name"]=> string(7) "admin_b" }
9. IntlChar
IntlChar:提供了一些可用于访问Unicode字符信息的实用方法的访问. 注意:必须安装Intl扩展才能使用!
var_dump(IntlChar::CODEPOINT_MAX);//int(1114111) echo '<br>'; var_dump(IntlChar::charName('+'));//string(9) "PLUS SIGN" echo '<br>'; var_dump(IntlChar::ispunct('?'));//bool(true)
内容版权声明:除非注明,否则皆为本站原创文章。