php 8%(⑵)
PHP的常量默许不辨别大小写,这在开发中容易造成没必要要的麻烦,比如常见的常量定义方式:
define('MY_CONSTANT', 'hello world!'); echo MY_Constant; // 输出 'hello world!', 注意大小写
在PHP 8%(⑵)中,引入了对常量大小写敏感的选项,以下代码演示了如何启用大小写敏感的常量:
define('MY_CONSTANT', 'hello world!', true); echo MY_Constant; // 等效于 undefined constant "MY_Constant" echo MY_CONSTANT; // 输出 'hello world!'
除常量,PHP 8%(⑵)还引入了函数和类的特性,以下是官方文档中一段示例代码:
class ShoppingCart { public function __construct(private array $products = []) {} public function add(int $product) { $this->products[] = $product; } public function getTotal(): int { return array_sum($this->products); } } $cart = new ShoppingCart([1, 2, 3]); $cart->add(4); echo $cart->getTotal(); // 输出 10
在上面的代码中,构造函数中的 `$products` 属性使用了新的写法,可以简洁的定义只读属性,并设置默许值。另外,使用了新的方法声明方式,比如 `public function getTotal(): int` 表示该方法将返回一个整数。
PHP 8%(⑵)还对字符串处理和Unicode支持做了改进。其中,`mbstring.extension` 现在默许是开启的,这意味着所有的mbstring函数都可以直接使用。同时,增加了 `str_contains()` 这个新函数用于判断字符串中会不会包括另外一个子串:
if (str_contains($string, $substring)) { // do something... }
最后,PHP 8%(⑵)对 JIT 编译机制进行了改进,在每一个要求中都会重置缓存,因此可以保证 JIT 编译器的稳定性和可靠性。
文章来源:丸子建站
文章标题:php 8%(⑵)
https://www.wanzijz.com/view/66649.html