Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php8.1

作者:巅峰战犯   发布日期:2025-03-14   浏览:88

<?php
// PHP 8.1 引入了多项新功能和改进,以下是几个示例代码及其解释:

// 1. 只读类 (Read-Only Classes)
class Point {
    public function __construct(
        public readonly int $x,
        public readonly int $y,
    ) {}
}

$point = new Point(1, 2);
// $point->x = 3; // 这行代码会报错,因为 $x 是只读属性

// 2. 新的 never 返回类型
function throwError(): never {
    throw new Exception('Error occurred');
}

// 3. 组合 union 类型和交集 intersection 类型
function logMessage(string|int $message): void {
    echo $message;
}

interface Logger {
    public function log(string $message): void;
}

interface Formatter {
    public function format(string $message): string;
}

class FileLogger implements Logger & Formatter {
    public function log(string $message): void {
        file_put_contents('log.txt', $message . PHP_EOL, FILE_APPEND);
    }

    public function format(string $message): string {
        return date('[Y-m-d H:i:s] ') . $message;
    }
}

// 4. Fibonacci 数列生成器
function fibonacci(int $limit): Generator {
    $current = 0;
    $next = 1;

    while ($current < $limit) {
        yield $current;

        $temp = $current;
        $current = $next;
        $next = $temp + $next;
    }
}

foreach (fibonacci(100) as $number) {
    echo $number . ', ';
}
?>

以上代码展示了 PHP 8.1 中的一些新特性,包括只读类、never 返回类型、组合类型以及生成器。希望这些示例能帮助你更好地理解 PHP 8.1 的新功能。

上一篇:php grpc

下一篇:php计算两个日期之间的天数

大家都在看

php session用法

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

php ||

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站