首页  >  文章  >  后端开发  >  PHP - 发现最新最好的

PHP - 发现最新最好的

WBOY
WBOY原创
2024-09-10 20:32:40731浏览

PHP  - Discover the Latest and Greatest

PHP 8.4 计划于 2024 年 11 月 21 日发布,包含一些令人兴奋的新功能和改进。在这篇博文中,我们将探讨一些最有趣的添加和更改:

  1. 新的数组辅助函数
  2. 属性挂钩
  3. 不带括号的“新”
  4. 已弃用隐式可为空的参数声明
  5. 新的多字节函数

1.新的数组辅助函数

PHP 8.4 中将添加以下数组辅助函数变体:

  • array_find()
  • array_find_key()
  • array_any()
  • array_all()

这些函数将采用一个数组和一个回调函数并返回以下内容:

functions Return value
array_find() Returns the first element that meets the callback condition; NULL otherwise.
array_find_key() Returns the key of the first element that meets the callback condition; NULL otherwise.
array_any() Returns true if at least one element matches the callback condition; false otherwise.
array_all() Returns true if all elements match the callback condition; false otherwise.

注意:array_find() 仅检索第一个匹配元素。对于多个匹配,请考虑使用 array_filter()。

例子

给定一个包含键值对和回调函数的数组:

$array = ['1'=> 'red', '2'=> 'purple', '3' => 'green']

function hasLongName($value) {
  return strlen($value) > 4;
}

以下是我们如何使用新功能:

  1. array_find():

      // Find the first color with a name length greater than 4
    
      $result1 = array_find($array, 'hasLongName');
    
      var_dump($result1);  // string(5) "purple"
    
  2. array_find_key():

      // Find the key of the first color with a name length greater than 4
    
      $result2 = array_find_key($array, 'hasLongName');
    
      var_dump($result2);  // string(1) "2"
    
  3. array_any():

      // Check if any color name has a length greater than 4
    
      $result3 = array_any($array, 'hasLongName');
    
      var_dump($result3);  // bool(true)
    
  4. array_all():

      // Check if all color names have a length greater than 4
    
      $result4 = array_all($array, 'hasLongName');
    
      var_dump($result4);  // bool(false)
    

2. 属性挂钩

PHP 8.4 引入了属性挂钩,提供了一种更优雅的方式来访问和修改类的私有或受保护属性。以前,开发人员依赖 getter、setter 和魔术方法(__get 和 __set)。现在,您可以直接在属性上定义 get 和 set 挂钩,从而减少样板代码。

我们可以使用代码块 {} 来包含属性挂钩,而不是用分号结束属性。
这些钩子是可选的,可以独立使用。通过排除其中之一,我们可以使属性只读或只写。

例子

class User
{
  public function __construct(private string $first, private string $last) {}

  public string $fullName {
    get => $this->first . " " . $this->last;

    set ($value) {
      if (!is_string($value)) {
        throw new InvalidArgumentException("Expected a string for full name,"
        . gettype($value) . " given.");
      }
      if (strlen($value) === 0) {
        throw new ValueError("Name must be non-empty");
      }
      $name = explode(' ', $value, 2);
      $this->first = $name[0];
      $this->last = $name[1] ?? '';
    }
  }
}

$user = new User('Alice', 'Hansen')
$user->fullName = 'Brian Murphy';  // the set hook is called
echo $user->fullName;  // "Brian Murphy"

如果 $value 是整数,则会抛出以下错误消息:

PHP Fatal error:  Uncaught InvalidArgumentException: Expected a string for full name, integer given.

如果 $value 为空字符串,则会抛出以下错误消息:

PHP Fatal error:  Uncaught ValueError: Name must be non-empty

3. 不带括号的“新”

PHP 8.4 引入了更简单的语法,允许您在新创建的对象上链接方法而无需括号。虽然这是一个微小的调整,但它会带来更干净、更简洁的代码。

(new MyClass())->getShortName();  // PHP 8.3 and older
new MyClass()->getShortName();  // PHP 8.4

除了在新创建的对象上链接方法之外,您还可以链接属性、静态方法和属性、数组访问,甚至直接调用类。例如:

new MyClass()::CONSTANT,
new MyClass()::$staticProperty,
new MyClass()::staticMethod(),
new MyClass()->property,
new MyClass()->method(),
new MyClass()(),
new MyClass(['value'])[0],

4. 已弃用隐式可为 null 的参数声明

在 PHP 8.4 之前,如果参数的类型为 X,它可以接受 null 值,而无需显式将 X 声明为可为 null。从 PHP 8.4 开始,如果没有在类型提示中明确声明可为空,则不能再声明空参数值;否则,将会触发弃用警告。

function greetings(string $name = null)  // fires a deprecation warning

为了避免警告,您必须在类型声明中使用问号 (?) 显式声明参数可以为 null。

function greetings(?string $name)

或者,

function greetings(?string $name = null)

5.新的多字节函数

多字节字符串是一个字符序列,其中每个字符可以使用多个字节的存储空间。这在具有复杂或非拉丁文字的语言中很常见,例如日语或中文。 PHP 中有几个多字节函数,如 mb_strlen()、mb_substr()、mb_strtolower()、mb_strpos() 等。但也有一些函数,如 trim()、ltrim()、rtrim()、ucfirst()、lcfirst () 等缺乏直接的多字节等价物。

感谢 PHP 8.4,其中将添加新的多字节函数。它们包括:mb_trim()、mb_ltrim()、mb_rtrim()、mb_ucfirst() 和 mb_lcfirst()。这些函数遵循原始函数签名,并带有附加的 $encoding 参数。
让我们讨论一下新的 mb_functions:

  1. mb_trim():

    删除多字节字符串开头和结尾的所有空白字符。

    函数签名:

      function mb_trim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
    

    参数:

    • $string:要修剪的字符串。
    • $characters:可选参数,包含要修剪的字符列表。
    • $encoding:encoding参数指定用于解释字符串的字符编码,确保多字节字符被正确处理。常见的编码包括UTF-8。
  2. mb_ltrim():

    删除多字节字符串开头的所有空白字符。

    函数签名:

      function mb_ltrim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
    
  3. mb_rtrim():

    删除多字节字符串末尾的所有空白字符。

    函数签名:

      function mb_rtrim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
    
  4. mb_ucfirst():

    将给定多字节字符串的第一个字符转换为标题大小写,其余字符保持不变。

    函数签名:

      function mb_ucfirst(string $string, ?string $encoding = null): string {}
    
  5. mb_lcfirst():

    与 mb_ucfirst() 类似,但它将给定多字节字符串的第一个字符转换为小写。

    函数签名:

      function mb_lcfirst(string $string, ?string $encoding = null): string {}
    

结论

我希望这篇博客能让您对 PHP 8.4 中即将发生的一些变化有一个很好的概述。新版本似乎引入了令人兴奋的更新,这将增强开发人员的体验。一旦正式发布我就迫不及待地开始使用它。
如需了解更多信息和更新,请访问官方 RFC 页面。

以上是PHP - 发现最新最好的的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn