목차
1. 열거형" >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
헤드라인 PHP8.1의 10가지 새로운 기능을 빠르게 사용해 보세요!

PHP8.1의 10가지 새로운 기능을 빠르게 사용해 보세요!

Dec 08, 2021 pm 02:05 PM
PHP 8.1

PHP 8.1에서 제공하는 상위 10가지 기능을 자세히 설명하여 프로젝트에서 해당 기능을 사용하고 PHP 경험을 향상시킬 수 있습니다. 초보자와 숙련된 개발자가 이 기사의 이점을 누릴 수 있습니다.

PHP 8.1에서 제공되는 상위 10가지 기능1. 열거형

2.Fiber(섬유)

3.never반환 유형

4.읽기 전용 속성 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 &#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;

?>
로그인 후 복사

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(&#39;https://www.google.com&#39;);

?>
로그인 후 복사

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 = &#39;1&#39;;
}

/**
 * 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 = &#39;2&#39;;
}

?>
로그인 후 복사

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 => &#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;]);

?>
로그인 후 복사

键不是从 0 开始的数组,或者键不是整数,或者键是整数但不按顺序出现的数组将评估为 false。

<?php

/**
 * Returns false as the first key does not start from zero.
 */
array_is_list([1 => &#39;apple&#39;, &#39;orange&#39;]);
/**
 * Returns false as the first key does not start from zero.
 */
array_is_list([1 => &#39;apple&#39;, 0 => &#39;orange&#39;]);
/**
 * Returns false as all keys are not integer.
 */
array_is_list([0 => &#39;apple&#39;, &#39;fruit&#39; => &#39;orange&#39;]);
/**
 * Returns false as the keys are not in sequential order.
 */
array_is_list([0 => &#39;apple&#39;, 2 => &#39;orange&#39;]); 

?>
로그인 후 복사

7. 新的fsync()fdatasync()函数

PHP 8.1 添加了对fsync()fdatasync()函数的支持。两者都与现有fflush()函数有相似之处,该函数当前用于将缓冲区刷新到操作系统中。然而,fsync()fdatasync()刷新该缓冲区到物理存储。它们之间的唯一区别是该fsync()函数在同步文件更改时包含元数据,而该fdatasync()

5. final 클래스 상수 🎜🎜6. 새로운 array_is_list() 함수 🎜🎜7. fdatasync() 함수 🎜🎜8. 문자열 키 배열 압축 풀기 지원 🎜🎜9. $_FILES디렉터리 업로드 코드에 대한 새로운 full_path> 키 🎜🎜10. 새로운 IntlDatePatternGenerator 클래스 🎜🎜🎜🎜1. 열거 🎜🎜PHP 8.1에서는 enum으로 축약되는 열거에 대한 지원이 추가되었습니다. 고정된 수의 가능한 값을 포함하는 항목별 유형입니다. 열거형을 사용하는 방법을 알아보려면 다음 코드 조각을 참조하세요. 🎜
<?php

/**
 * Declare a variable and assign a filename.
 */
$fileName = &#39;notes.txt&#39;;
/**
 * Create the file with read and write permission.
 */
$file = fopen($fileName, &#39;w+&#39;);
/**
 * Add some text into the file.
 */
fwrite($file, &#39;Paragraph 1&#39;);
/**
 * Add a line break into the file.
 */
fwrite($file, "\r\n");
/**
 * Add some more text into the file.
 */
fwrite($file, &#39;Paragraph 2&#39;);
/**
 * 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);

?>
로그인 후 복사
로그인 후 복사
🎜2. Fiber 🎜🎜PHP 8.1에는 PHP에서 동시 코드 실행을 허용하는 하위 수준 구성 요소인 Fiber에 대한 지원이 추가되었습니다. Fiber는 자체 변수와 상태 스택을 포함하는 코드 블록입니다. 이러한 파이버는 애플리케이션 스레드로 간주될 수 있으며 기본 프로그램에서 시작할 수 있습니다. 일단 시작되면 기본 프로그램은 Fiber를 일시 중지하거나 종료할 수 없습니다. Fiber 코드 블록 내에서만 일시 중지하거나 종료할 수 있습니다. Fiber가 일시 중지된 후에는 제어가 다시 기본 프로그램으로 반환되며 일시 중지된 시점부터 Fiber를 계속 실행할 수 있습니다. 🎜
🎜Fiber 자체는 여러 Fiber 또는 메인 스레드와 Fiber가 동시에 실행되는 것을 허용하지 않습니다. 그러나 실행 스택을 효율적으로 관리하고 비동기 실행을 허용하는 것은 PHP 프레임워크의 큰 이점입니다. 🎜
🎜Fiber 사용 방법을 알아보려면 다음 코드 조각을 참조하세요. 🎜
<?php

/**
 * Declare an array
 */
$fruits1 = [&#39;Jonathan Apples&#39;, &#39;Sapote&#39;];
/**
 * Declare another array
 */
$fruits2 = [&#39;Pomelo&#39;, &#39;Jackfruit&#39;];
/**
 * Merge above two arrays using array unpacking.
 */
$unpackedFruits = [...$fruits1, ...$fruits2, ...[&#39;Red Delicious&#39;]];
/**
 * 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);

?>
로그인 후 복사
로그인 후 복사
🎜3.never 반환 유형🎜🎜PHP 8.1에는 never라는 반환 유형이 추가되었습니다. never 유형은 지정된 작업 세트를 수행한 후 함수가 프로그램 실행을 종료함을 나타내는 데 사용할 수 있습니다. exit() 또는 die() 함수를 호출하여 예외를 발생시키면 됩니다. 🎜
🎜 never 반환 유형은 void 반환 유형과 유사합니다. 그러나 void 반환 유형은 함수가 지정된 작업 세트를 완료한 후에도 계속 실행됩니다. 🎜
🎜반환되지 않는 유형을 사용하는 방법을 이해하려면 다음 코드 조각을 참조하세요. 🎜
<?php

/**
 * Check if the user has submitted the form.
 */
if ($_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {
    /**
     * 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>
로그인 후 복사
로그인 후 복사
🎜4.readonly attribute🎜🎜PHP 8.1에는 readonly라는 클래스 속성이 추가되었습니다. 읽기 전용으로 선언된 클래스 속성은 한 번만 초기화할 수 있습니다. 내부에 설정된 값은 변경할 수 없습니다. 값을 강제로 업데이트하려고 하면 애플리케이션에서 오류가 발생합니다. 읽기 전용 속성을 사용하는 방법을 알아보려면 다음 코드 조각을 참조하세요. 🎜
<?php

/**
 * Define a default date format.
 */
$skeleton = "YYYY-MM-dd";
/**
 * Parse a time string (for today) according to a specified format.
 */
$today = \DateTimeImmutable::createFromFormat(&#39;Y-m-d&#39;, date(&#39;Y-m-d&#39;));
/**
 * ===========================
 * PRINTING DATE IN USA FORMAT
 * ===========================
 * Initiate an instance for the IntlDatePatternGenerator class
 * and provide the locale information.
 * In the below example, I&#39;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&#39;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";

?>
로그인 후 복사
로그인 후 복사
🎜5. final 클래스 상수🎜🎜PHP 8.1에는 final이라는 클래스 상수에 대한 지원이 추가되었습니다. 최종 클래스 상수는 상속을 통해서도 수정할 수 없습니다. 즉, 하위 클래스에서 확장하거나 재정의할 수 없습니다. 🎜
🎜이 플래그는 클래스 외부에서 접근할 수 없기 때문에 private 상수에 사용할 수 없습니다. final 및 private 상수를 선언하면 치명적인 오류가 발생합니다. 🎜
🎜최종 로고를 사용하는 방법을 보려면 아래 코드 조각을 참조하세요. 🎜rrreee🎜6. 새로운 array_is_list() 함수 🎜🎜PHP 8.1에는 array_is_list()라는 배열 함수가 추가되었습니다. 지정된 배열에 0부터 시작하는 모든 연속 정수가 있는지 여부를 식별합니다. 이 함수는 배열이 의미론적 값 목록(키가 0에서 시작하고 모두 정수이며 사이에 간격이 없는 배열)인 경우 true를 반환합니다. 또한 빈 배열에 대해서도 true를 반환합니다. array_is_list() 함수를 사용하는 방법을 알아보려면 다음 코드 조각을 참조하세요. 🎜rrreee🎜키가 0 기반이 아니거나, 키가 정수가 아니거나, 키가 정수이지만 순서가 잘못된 배열은 false로 평가됩니다. 🎜rrreee🎜7. 새로운 fsync()fdatasync() 함수 🎜🎜PHP 8.1에 fsync() 지원이 추가되었습니다. fdatasync() 함수용입니다. 둘 다 현재 버퍼를 운영 체제로 플러시하는 데 사용되는 기존 ffflush() 함수와 유사합니다. 그러나 fsync()fdatasync()는 이 버퍼를 물리적 저장소로 플러시합니다. 이들 간의 유일한 차이점은 fsync() 함수는 파일 변경 사항을 동기화할 때 메타데이터를 포함하는 반면, fdatasync() 함수는 메타데이터를 포함하지 않는다는 점입니다. 🎜

fsync()函数将采用文件指针并尝试将更改提交到磁盘。成功时返回 true,失败时返回 false,如果资源不是文件,则会发出警告。fdatasync()函数的工作方式相同,但速度稍快一些,因为 fsync() 将尝试完全同步文件的数据更改和有关文件的元数据(上次修改时间等),这在技术上是两次磁盘写入。

请参阅以下代码片段以了解如何使用 fsync() 和 fdatasync() 函数。

<?php

/**
 * Declare a variable and assign a filename.
 */
$fileName = &#39;notes.txt&#39;;
/**
 * Create the file with read and write permission.
 */
$file = fopen($fileName, &#39;w+&#39;);
/**
 * Add some text into the file.
 */
fwrite($file, &#39;Paragraph 1&#39;);
/**
 * Add a line break into the file.
 */
fwrite($file, "\r\n");
/**
 * Add some more text into the file.
 */
fwrite($file, &#39;Paragraph 2&#39;);
/**
 * 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 = [&#39;Jonathan Apples&#39;, &#39;Sapote&#39;];
/**
 * Declare another array
 */
$fruits2 = [&#39;Pomelo&#39;, &#39;Jackfruit&#39;];
/**
 * Merge above two arrays using array unpacking.
 */
$unpackedFruits = [...$fruits1, ...$fruits2, ...[&#39;Red Delicious&#39;]];
/**
 * 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[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {
    /**
     * 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(&#39;Y-m-d&#39;, date(&#39;Y-m-d&#39;));
/**
 * ===========================
 * PRINTING DATE IN USA FORMAT
 * ===========================
 * Initiate an instance for the IntlDatePatternGenerator class
 * and provide the locale information.
 * In the below example, I&#39;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&#39;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

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)