您好,欢迎访问一九零五行业门户网

PHP8.1的十大新功能,快用起来吧!

php 8.1 现已推出,它附带了新功能和性能改进——最令人兴奋的是新的 jit 编译器。它最近于 2021 年 11 月 25 日发布。
我将详细演示 php 8.1 提供的 10 大特性,以便您可以开始在您的项目中使用它们,并改善您的 php 体验。初学者和有经验的开发人员可以从本文中受益。
php 8.1 提供的 10 大功能1.枚举
2.fiber(纤维)
3.never返回类型
4.readonly属性
5.final类常量
6.新的array_is_list()函数
7.新的fsync()和fdatasync()函数
8.对字符串键数组解包的支持
9.$_files新的用于目录上传的full_path键
10.新的intldatepatterngenerator类
1. 枚举php 8.1 添加了对枚举的支持,简写为 enum 。它是一种逐项类型,包含固定数量的可能值。请参阅以下代码片段以了解如何使用枚举。
<?php/** * declare an enumeration. * it can also contain an optional 'string' or 'int' value. this is called backed enum. * backed enums (if used) should match the following criteria: * - declare the scalar type, whether string or int, in the enum declaration. * - all cases have values. * - all cases contain the same scalar type, whether string or int. * - each case has a unique value. */enum userrole: string { case admin = '1'; case guest = '2'; case writer = '3'; case editor = '4';}/** * you can access a case by using * the '::' scope resolution operator. * and, to get the name of the enum case, you * can use the '->' followed by the attribute 'name'. */echo userrole::writer->name;/** * to get the value of the enum case, you can * use the '->' followed by the attribute 'value'. */echo userrole::writer->value;?>
2. fiber(纤维)php 8.1 添加了对 fiber 的支持,这是一个低级组件,允许在 php 中执行并发代码。fiber 是一个代码块,它包含自己的变量和状态堆栈。这些 fiber 可以被视为应用程序线程,可以从主程序启动。一旦启动,主程序将无法挂起或终止 fiber。它只能从 fiber 代码块内部暂停或终止。在 fiber 挂起后,控制权再次返回到主程序,它可以从挂起的点继续执行 fiber。
fiber 本身不允许同时执行多个 fiber 或主线程和一个 fiber。但是,对于 php 框架来说,高效管理执行堆栈并允许异步执行是一个巨大的优势。
请参阅以下代码片段以了解如何使用 fiber。
<?php/** * initialize the fiber. */$fiber = new fiber(function(): void { /** * print some message from inside the fiber. * before the fiber gets suspended. */ echo "welcome to fiber!\n"; /** * suspend the fiber. */ fiber::suspend(); /** * print some message from inside the fiber. * after the fiber gets resumed. */ echo "welcome back to fiber!\n";});/** * print a message before starting a fiber. */echo "starting a fiber\n";/** * start the fiber. */$fiber->start();/** * fiber has been suspened from the inside. * print some message, and then resume the fiber. */echo "fiber has been suspended\n";echo "resuming the fiber\n";/** * resume the fiber. */$fiber->resume();/** * end of the example. */echo "fiber completed execution\n";?>
3.never返回类型php 8.1 添加了名为never的返回类型。该never类型可用于指示函数将在执行一组指定的任务后终止程序执行。这可以通过抛出异常、调用exit()或die()函数来完成。
never返回类型类似于void返回类型。但是,void返回类型在函数完成一组指定的任务后继续执行。
请参阅以下代码片段以了解如何使用 never 返回类型。
<?php/** * route class */class route { /** * constructor of the class * @return void */ public function __construct() { } /** * redirect to a page * this function redirects to an url specified by the user. * @method redirect() * @param string $url * @param integer $httpcode * @author tara prasad routray <someemailaddress@example.com> * @access public * @return never */ public static function redirect($url, $httpcode = 301): never { /** * redirect to the url specified. */ header("location: {$url}", true, $httpcode); die; }}route::redirect('https://www.google.com');?>
4.readonly属性php 8.1 添加了名为readonly的类属性。已声明为只读的类属性只能初始化一次。里面设置的值不能改变。如果尝试强行更新该值,应用程序将抛出错误。请参阅以下代码片段以了解如何使用只读属性。
<?php/** * user class */class user { /** * declare a variable with readonly property. * @var $authuserid * @access public */ public readonly int $authuserid; /** * constructor of the class. * @param integer $userid * @return void */ public function __construct($userid) { /** * change the value of the property as specified. * updating the value of readonly properties are * allowed only through the constructor. */ $this->authuserid = $userid; } /** * update auth user id * this function tries to update the readonly property (which is not allowed). * @method updateauthuserid() * @param integer $userid * @author tara prasad routray <someemailaddress@example.com> * @access public * @return void */ public function updateauthuserid($userid) { /** * change the value of the property as specified. * executing this function will throw the following error; * php fatal error: uncaught error: cannot modify readonly property user::$authuserid */ $this->authuserid = $userid; }}/** * initialize the class and update the value of the readonly property. */$user = new user(30);/** * print the readonly property value. * this will print 30. */echo $user->authuserid;/** * call another function inside the class and try to update the class property. */$user->updateauthuserid(50);/** * print the readonly property value. */echo $user->authuserid;?>
5. final类常量php 8.1 添加了对名为final的类常量的支持。最终类常量不能被修改,即使是通过继承,这意味着它们不能被子类扩展或覆盖。
这个标志不能用于私有常量,因为它不能在类之外被访问。声明 final 和 private 常量将导致致命错误。
请参阅以下代码片段以了解如何使用最终标志。
<?php/** * userrole class */class userrole { /** * declare a final class constant with a value. */ final public const admin = '1';}/** * user class extending the userrole class */class user extends userrole { /** * declare another constant with the same name * as of the parent class to override the value. * * note: overriding the value will throw the following error: * php fatal error: user::admin cannot override final constant userrole::admin */ public const admin = '2';}?>
6. 新的 array_is_list() 函数php 8.1 添加了名为array_is_list()的数组函数。它标识指定的数组是否具有从 0 开始的所有连续整数。如果数组是值的语义列表(一个数组,其键从 0 开始,都是整数,并且之间没有间隙),则此函数返回 true。对于空数组,它也返回 true。请参阅以下代码片段以了解如何使用 array_is_list() 函数。
<?php/** * returns true for empty array. */array_is_list([]);/** * returns true for sequential set of keys. */array_is_list([1, 2, 3]);/** * returns true as the first key is zero, and keys are in sequential order. * it is same as [0 => 'apple', 1 => 2, 2 => 3] */array_is_list(['apple', 2, 3]);/** * returns true as the first key is zero, and keys are in sequential order. * it is same as [0 => 'apple', 1 => 'scissor'] */array_is_list(['apple', 'orange']);/** * returns true as the first key is zero, and keys are in sequential order. * it is same as [0 => 'apple', 1 => 'scissor'] */array_is_list([0 => 'apple', 'orange']);/** * returns true as the first key is zero, and keys are in sequential order. */array_is_list([0 => 'rock', 1 => 'scissor']);?>
键不是从 0 开始的数组,或者键不是整数,或者键是整数但不按顺序出现的数组将评估为 false。
<?php/** * returns false as the first key does not start from zero. */array_is_list([1 => 'apple', 'orange']);/** * returns false as the first key does not start from zero. */array_is_list([1 => 'apple', 0 => 'orange']);/** * returns false as all keys are not integer. */array_is_list([0 => 'apple', 'fruit' => 'orange']);/** * returns false as the keys are not in sequential order. */array_is_list([0 => 'apple', 2 => 'orange']); ?>
7. 新的fsync()和fdatasync()函数php 8.1 添加了对fsync()和fdatasync()函数的支持。两者都与现有fflush()函数有相似之处,该函数当前用于将缓冲区刷新到操作系统中。然而,fsync()和fdatasync()刷新该缓冲区到物理存储。它们之间的唯一区别是该fsync()函数在同步文件更改时包含元数据,而该fdatasync()函数不包含元数据。
fsync()函数将采用文件指针并尝试将更改提交到磁盘。成功时返回 true,失败时返回 false,如果资源不是文件,则会发出警告。fdatasync()函数的工作方式相同,但速度稍快一些,因为 fsync() 将尝试完全同步文件的数据更改和有关文件的元数据(上次修改时间等),这在技术上是两次磁盘写入。
请参阅以下代码片段以了解如何使用 fsync() 和 fdatasync() 函数。
<?php/** * declare a variable and assign a filename. */$filename = 'notes.txt';/** * create the file with read and write permission. */$file = fopen($filename, 'w+');/** * add some text into the file. */fwrite($file, 'paragraph 1');/** * add a line break into the file. */fwrite($file, "\r\n");/** * add some more text into the file. */fwrite($file, 'paragraph 2');/** * you can use both the fsync() or fdatasync() functions * to commit changs to disk. */fsync($file); // or fdatasync($file)./** * close the open file pointer. */fclose($file);?>
8. 对字符串键数组解包的支持php 8.1 添加了对字符串键数组解包的支持。为了解压数组,php 使用展开(…)运算符。php 7.4 中引入了这个运算符来合并两个或多个数组,但语法更简洁。但在 php 8.1 之前,展开运算符仅支持带数字键的数组。请参阅以下代码片段以了解如何将展开运算符用于字符串键控数组。
<?php/** * declare an array */$fruits1 = ['jonathan apples', 'sapote'];/** * declare another array */$fruits2 = ['pomelo', 'jackfruit'];/** * merge above two arrays using array unpacking. */$unpackedfruits = [...$fruits1, ...$fruits2, ...['red delicious']];/** * print the above unpacked array. * this will print: * array(5) { * [0]=> * string(15) "jonathan apples" * [1]=> * string(6) "sapote" * [2]=> * string(6) "pomelo" * [3]=> * string(9) "jackfruit" * [4]=> * string(13) "red delicious" * } */var_dump($unpackedfruits);?>
9. $_files 新的用于目录上传的 full_path 键php 8.1 添加了对$_files全局变量中full_path新键的支持。在 php 8.1 之前,$_files没有存储到服务器的相对路径或确切目录。因此,您无法使用 html 文件上传表单上传整个目录。新full_path键解决了这个问题。它存储相对路径并在服务器上重建确切的目录结构,使目录上传成为可能。请参阅以下代码片段以了解如何将full_path键与$_files全局变量一起使用。
<?php/** * check if the user has submitted the form. */if ($_server['request_method'] === 'post') { /** * print the $_files global variable. this will display the following: * array(1) { * ["myfiles"]=> array(6) { * ["name"]=> array(2) { * [0]=> string(9) "image.png" * [1]=> string(9) "image.png" * } * ["full_path"]=> array(2) { * [0]=> string(25) "folder1/folder2/image.png" * [1]=> string(25) "folder3/folder4/image.png" * } * ["tmp_name"]=> array(2) { * [0]=> string(14) "/tmp/phpv1j3em" * [1]=> string(14) "/tmp/phpzbmakt" * } * // ... + error, type, size * } * } */ var_dump($_files);}?><form action="" method="post" enctype="multipart/form-data"> <input name="myfiles[]" type="file" webkitdirectory multiple /> <button type="submit">submit</button></form>
10. 新的intldatepatterngenerator类php 8.1 添加了对新intldatepatterngenerator类的支持。在 php 8.1 之前,只能使用intldateformatter。虽然它支持昨天、今天和明天使用的八种预定义格式,但是这些格式和intldatepatterngenerator不太一样。这个类允许指定日期、月份和时间的格式,并且顺序将由类自动处理。请参阅以下代码片段以了解如何使用 intldatepatterngenerator 类。
<?php/** * define a default date format. */$skeleton = "yyyy-mm-dd";/** * parse a time string (for today) according to a specified format. */$today = \datetimeimmutable::createfromformat('y-m-d', date('y-m-d'));/** * =========================== * printing date in usa format * =========================== * initiate an instance for the intldatepatterngenerator class * and provide the locale information. * in the below example, i've used locale: en_us. */ $intldatepatterngenerator = new \intldatepatterngenerator("en_us");/** * get the correct date format for the locale: en_us. * following function "getbestpattern" will return: * mm/dd/yyyy */$enusdatepattern = $intldatepatterngenerator->getbestpattern($skeleton);/** * use the "formatobject" function of intldateformatter to print as per specified pattern. * this will print the following: * date in en-us: 12/03/2021 */echo "date in en-us: ". \intldateformatter::formatobject($today, $enusdatepattern, "en_us"). "\n";/** * ============================= * printing date in india format * ============================= * initiate an instance for the intldatepatterngenerator class * and provide the locale information. * in the below example, i've used locale: en_in. */$intldatepatterngenerator = new \intldatepatterngenerator("en_in");/** * get the correct date format for the locale: en_in. * following function "getbestpattern" will return: * dd/mm/yyyy */$enindatepattern = $intldatepatterngenerator->getbestpattern($skeleton);/** * use the "formatobject" function of intldateformatter to print as per specified pattern. * this will print the following: * date in en-in: 03/12/2021 */echo "date in en-in: ". \intldateformatter::formatobject($today, $enindatepattern, "en_in"). "\n";?>
点赞!您已经完成了 php 8.1 提供的功能的学习。现在您可以继续并开始在您当前或即将进行的项目中实现上述功能。
原文:https://levelup.gitconnected.com/top-10-php-8-1-features-you-should-start-using-now-7161b91275fd
其它类似信息

推荐信息