php最新稳定版本 php最新版本最多少( 二 )


这一新特性非常有用 , 开发者不必担心代码存在内存泄露了 。大多数 PHP 开发者可能对此不关心 , 但是当你在编写长时间运行的进程时 , 那你就一定要提防这个问题了 , 比如使用 ReactPHP 进行事件驱动编程时 。用了 WeakMap 后引用的对象 , 就会在失效时自动被垃圾回收 。
如果你在数组中做同样的操作 , 仍然会持有该对象的引用的 , 但是会导致内存泄露 。
示例代码如下:
<?phpdeclare(strict_types=1);class FooBar {public WeakMap $cache;public function __construct() {$this->cache = new WeakMap();}public function getSomethingWithCaching(object $obj) {return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj);}public function computeSomethingExpensive(object $obj) {var_dump("I got called");return rand(1, 100);}}$cacheObject = new stdClass;$obj = new FooBar;// "I got called" 只会打印一次$obj->getSomethingWithCaching($cacheObject);$obj->getSomethingWithCaching($cacheObject);var_dump(count($obj->cache));// 删除该对象后 WeakMap 会释放相应内存unset($cacheObject);var_dump(count($obj->cache));exit;对应的运行结果:
变量语法调整
8的new 和 instanceof 关键字支持用于任意表达式了 , 示例代码如下
<?phpdeclare(strict_types=1);class Foo {}class Bar {}$names = ['Foo', 'Bar'];$class = new ($names[array_rand($names)]);var_dump($class);exit;运行结果:
对象的类名字面量
8 中支持使用 $object::class 获取对象的类名 , 返回结果和 get_class($object) 是一样的 。示例代码:
<?phpdeclare(strict_types=1);class Test {}$test = new Test();var_dump($test::class);var_dump(get_class($test));exit;运行结果:
参数列表中允许出现可选的尾部逗号
和数组中的尾部逗号一样 , 8也支持在参数列表中定义一个尾部逗号了 。示例代码:
<?phpdeclare(strict_types=1);function method_with_many_arguments($a,$b,$c,$d,) {var_dump("this is valid syntax");}method_with_many_arguments(1,2,3,4,);exit;上述代码运行结果:
Stringable 接口
8 引入了新的 Stringable 接口 , 只要某个类实现了 __toString 方法 , 就会被当作自动实现了 Stringable 接口(这一点和 Go 接口实现有些像) , 而不需要显式与声明实现该接口 , 示例代码:
<?phpdeclare(strict_types=1);class Foo {public function __toString() {return 'I am a class';}}$obj = new Foo;var_dump($obj instanceof Stringable);exit;运行结果:
throw 已经支持被用作表达式
8支持 throw 语句可以用在只允许表达式出现的地方 , 比如箭头函数、合并运算符和三元运算符等:
示例代码
<?phpdeclare(strict_types=1);$callable = fn() => throw new Exception();$nullableValue = https://www.520longzhigu.com/shenghuo/null;// $value 是非空的$value = $nullableValue ?? throw new \InvalidArgumentException();exit;捕获异常而不存储到变量
8可以编写 catch (Exception) 代码来捕获异常 , 但是不用将其存储到一个变量里:
<?phpdeclare(strict_types=1);$nullableValue = https://www.520longzhigu.com/shenghuo/null;try {$value = $nullableValue ?? throw new \InvalidArgumentException();} catch (\InvalidArgumentException) {var_dump("Something went wrong");}exit;上述代码运行结果:
PHP 8 的新增对注解的支持
注解实际上包含了多个 RFC:
https://wiki.php.net/rfc/attributes_v2https://wiki.php.net/rfc/attribute_amendmentshttps://wiki.php.net/rfc/shorter_attribute_syntaxhttps://wiki.php.net/rfc/shorter_attribute_syntax_change注解是 PHP 8 引入的最大新特性之一 , 一开始理解起来可能有点困难(如果你有 Java 基础的话理解起来会相对简单) 。


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: