PHP 8.1 で提供されるトップ 10 の機能を順に説明します。これにより、これらの機能をプロジェクトで使用し始めて、PHP エクスペリエンスを向上させることができます。初心者も経験豊富な開発者も、この記事から恩恵を受けることができます。
PHP 8.1 で提供される上位 10 の関数1.Enumeration
2.Fiber
3.
never戻り値の型4.
プロパティ5.
クラス定数6.New
function7. 新しい
および fdatasync()
function8. 文字列キーの適切なサポート配列の解凍
9.
$_FILESディレクトリ アップロード用の新しい full_path
キー10.New
Class
1. 列挙PHP 8.1 では、列挙 (
enum と省略) のサポートが追加されました。これは、固定数の可能な値を含む項目化されたタイプです。列挙型の使用方法については、次のコード スニペットを参照してください。 <pre class='brush:php;toolbar:false;'><?php
/**
* Declare an enumeration.
* It can also contain an optional &#39;string&#39; or &#39;int&#39; 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 = &#39;1&#39;;
case GUEST = &#39;2&#39;;
case WRITER = &#39;3&#39;;
case EDITOR = &#39;4&#39;;
}
/**
* You can access a case by using
* the &#39;::&#39; scope resolution operator.
* And, to get the name of the enum case, you
* can use the &#39;->&#39; followed by the attribute &#39;name&#39;.
*/
echo UserRole::WRITER->name;
/**
* To get the value of the enum case, you can
* use the &#39;->&#39; followed by the attribute &#39;value&#39;.
*/
echo UserRole::WRITER->value;
?></pre>
2. Fiber
PHP 8.1 では、PHP でのコードの同時実行を可能にする低レベル コンポーネントである
Fiber のサポートが追加されています。ファイバーは、独自の変数と状態スタックを含むコードのブロックです。これらのファイバーはアプリケーション スレッドと考えることができ、メイン プログラムから開始できます。メインプログラムが開始されると、Fibre を一時停止または終了することはできません。一時停止または終了は、Fibre コード ブロック内からのみ行うことができます。 Fiber が一時停止された後、制御は再びメイン プログラムに戻り、一時停止時点から Fiber の実行を継続できます。
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戻り値の型は、
never return 型の使用方法を理解するには、次のコード スニペットを参照してください。void
の戻り値の型と似ています。ただし、void
戻り値の型は、関数が指定された一連のタスクを完了した後も実行を継続します。
<?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.
readonlyAttribute
PHP 8.1 では、
readonly という名前のクラス属性が追加されました。読み取り専用として宣言されたクラス プロパティは 1 回だけ初期化できます。内部に設定されている値は変更できません。値を強制的に更新しようとすると、アプリケーションはエラーをスローします。読み取り専用プロパティの使用方法については、次のコード スニペットを参照してください。 <pre class='brush:php;toolbar:false;'><?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;
?></pre>
5.
クラス定数
PHP 8.1 では、
final という名前のクラス定数のサポートが追加されました。最終クラス定数は、継承を介しても変更できません。つまり、サブクラスによって拡張したりオーバーライドしたりすることはできません。
final フラグの使用方法を理解するには、次のコード スニペットを参照してください。
<?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() 関数の使用方法については、次のコード スニペットを参照してください。 <pre class='brush:php;toolbar:false;'><?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 => &#39;apple&#39;, 1 => 2, 2 => 3]
*/
array_is_list([&#39;apple&#39;, 2, 3]);
/**
* Returns true as the first key is zero, and keys are in sequential order.
* It is same as [0 => &#39;apple&#39;, 1 => &#39;scissor&#39;]
*/
array_is_list([&#39;apple&#39;, &#39;orange&#39;]);
/**
* Returns true as the first key is zero, and keys are in sequential order.
* It is same as [0 => &#39;apple&#39;, 1 => &#39;scissor&#39;]
*/
array_is_list([0 => &#39;apple&#39;, &#39;orange&#39;]);
/**
* Returns true as the first key is zero, and keys are in sequential order.
*/
array_is_list([0 => &#39;rock&#39;, 1 => &#39;scissor&#39;]);
?></pre>
キーが 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

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境
