已经2025年不会还没尝试过 php8 吧! | php 技术论坛-380玩彩网官网入口

2016 年的时候第一次接触到 php,貌似是 php5.6 的版本,采用lamp 架构快速构建 web 应用;当时的互联网公司使用 php 的应该还是蛮多的,百度、微博也都在使用,鸟哥应该算是国内 php 明星级别的人物;后面 2019年的时候记得当时面试中必不可少的是会问到 php5和php7的区别是什么, 性能上来说确实是非一般的提升,主要是对类型的底层结构都进行了调整;后来 2020 年似乎整个世界环境都不太好,php 在国内也走下坡路,虽然推出了 php8 ,但国内也开始了一阵 php转golang的风,不少公司的技术也开始转型;2021年,核心贡献者 nikita popov 离开 php,迫使基金会的事项不得不加速提上进程,也让 php 再一次续命;此后每年 php 迭代一个大版本,2024年底也发布了 php8.4,按照计划 2025 年也会推出 php8.5 。

所以你有用到 php8 ,或者说你有在公司级项目推 php8 的落地吗?我之前工作的地方依然还有 php5.6,当然那是比较早的项目,目前公司如果还在用php,应该大多数是 php7 了吧。so 即使工作中没用到 php8,但是你可以用php8为自己带来财富,不是么,如果你想要自己做一些什么,php绝对是效率。php is not dead !

php 8.0 是 php 语言的一次重大更新。 它包含了很多新功能与优化项, 包括命名参数、联合类型、注解、构造器属性提升、match 表达式、nullsafe 运算符、jit,并改进了类型系统、错误处理、语法一致性。

1.1 命名参数(named arguments)

  • php8.0 允许您按名称指定参数,而不是按位置指定。这在调用具有许多参数的函数时特别有用,使代码更具可读性。再也不用担心可能由于参数数量繁多,导致位置传递错误。
  • 仅仅指定必填参数,跳过可选参数
  • 参数的顺序无关、自己就是文档(self-documented)
// named arguments
$min = 3600;
$max = 7200;
echo 'rand-' . random_int($min, $max) . php_eol;
echo 'rand-' . random_int(max:$max, min:$min) . php_eol;

1.2 注解(attributes)

  • 注解在代码中为类和属性提供元数据。这些元数据可以在运行时通过反射(reflection)读取,并作出相应处理。
  • 注解 php 原生语法来使用结构化的元数据,而非 phpdoc 声明。
  • 注解用于软件架构中常见的需求,例如依赖注入、验证、日志记录等。

简单的注解

  • #[attribute]声明注解类
    • 这个注解类被声明为可以用于类和属性(target_class | target_property)
// 定义一个简单的注解类
#[attribute(attribute::target_class | attribute::target_property)]
class myattribute
{
// 它定义了两个属性name和value
    public function __construct(
        public string $name,
        public int $value
    ) {}
}
  • 使用注解
    • 把自定义的 myattribute 注解类,使用到testclass类和它的$property属性上。
// 另一个类中使用这个注解
#[myattribute(name: 'testclass', value: 10)]
class testclass
{
    #[myattribute(name: 'testproperty', value: 20)]
    public string $property;
}
  • 读取注解
    • 可以使用反射对象 reflectionclass
// 创建一个reflectionclass对象,用来获取 testclass 相关信息
$reflectionclass = new reflectionclass(testclass::class);
// 获取某个类的注解
$classattributes = $reflectionclass->getattributes(myattribute::class);
foreach ($classattributes as $attribute) {
    $instance = $attribute->newinstance();
    echo "class attribute: name = {$instance->name}, value = {$instance->value}" . php_eol;
}
// 获取某个类的属性注解
$reflectionproperty = $reflectionclass->getproperty('property');
$propertyattributes = $reflectionproperty->getattributes(myattribute::class);
foreach ($propertyattributes as $attribute) {
    $instance = $attribute->newinstance();
    echo "property attribute: name = {$instance->name}, value = {$instance->value}" . php_eol;
}

具体的例子

  • 定义一个validation注解类,利用注解自动验证数据;
  • helpvalidate 方法被修改为对 rules 数组中的每一个规则进行迭代并进行验证。这种设计允许您轻松添加更多规则而无需修改现有的代码逻辑。
#[attribute(attribute::target_property)]
class validation
{
    public function __construct(
        public string $rule
    ) {}
}
class user
{
    #[validation('required|string')]
    public string $username;
    #[validation('required|email')]
    public string $email;
}
/**
 * 使用注解判断某个对象的属性是否合法
 *
 * @param object $object
 * @return void
 */
function helpvalidate(object $object): void
{
    $reflectionclass = new reflectionclass($object);
    // 获取某个对象所有的属性
    foreach ($reflectionclass->getproperties() as $property) {
        // 获取这个注解的属性
        $attributes = $property->getattributes(validation::class);
        // 对所有属性进行检查
        foreach ($attributes as $attribute) {
            $validation = $attribute->newinstance();
            $value = $property->getvalue($object);
            $rules = explode("|", $validation->rule);
            foreach ($rules as $rule) {
                if ($rule === 'required') {
                    if (empty($value)) {
                        throw new exception("{$property->getname()} is required.");
                    }
                } elseif ($rule === 'email') {
                    if (!filter_var((string)$value, filter_validate_email)) {
                        throw new exception("{$property->getname()} is not a valid email.");
                    }
                }
            }
        }
    }
}
$user = new user();
$user->username = 'mochi';
$user->email = 'mochi.com';
try {
    helpvalidate($user);
    echo "validation passed.";
} catch (exception $e) {
    echo $e->getmessage();
}

1.3 构造器属性提升(constructor property promotion)

  • 更少的代码来定义并初始化属性;
  • 语法糖,相当于省略构造函数的参数作为类的成员变量的定义;
  • 使用构造器属性提升可以减少重复代码,从而使代码更简洁和更具可读性;
class point {
    public function __construct(
      public float $x = 0.0,
      public float $y = 0.0,
      public float $z = 0.0,
    ) {}
}

1.4 联合类型(union types)

  • 相较于以前的 phpdoc 声明类型的组合, 现在可以用原生支持的联合类型声明取而代之,并在运行时得到校验;
  • 通过 declare(strict_types=1); 强制执行严格类型检查,确保传递的类型符合预期;
  • 联合类型(union types)允许变量、参数和返回值同时接受多个类型;
  • 通过联合类型的功能,可以简化代码中类型的定义,提升代码的灵活性;

// 记得加上
declare(strict_types=1);
class number {
    public function __construct(
      private int|float $number
    ) {}
    function getnumber() :int|float {
        return $this->number;
    }
}
echo gettype((new number(1))->getnumber()) .php_eol;  // integer
echo gettype((new number(3.14))->getnumber()).php_eol; // double
// 如果没有 strict_types = 1 php就会强转成 integer
// fatal error: uncaught typeerror: number::__construct(): argument #1 ($number) must be of type int|float, string given, called 
echo gettype((new number('0'))->getnumber()).php_eol; // typeerror

1.5 match 表达式(match expression)

  • 新的 match 类似于 switch;
  • match 是一个表达式,它可以储存到变量中亦可以直接返回;
  • match 分支仅支持单行,它不需要一个 break; 语句;
  • match 使用严格比较,这样对类型来说是一个不错的点,相当于三个等号=== ;
  • match 语法更简洁,更具可读性,有助于减少错误,并提高代码清晰度;
echo match (8.0) {
    '8.0' => "oh no!",
    8.0 => "this is what i expected",
};

1.6 nullsafe 运算符(nullsafe operator)

  • nullsafe 运算符 ?->,它提供了一种安全访问对象属性或方法的方法,而不会抛出错误;
  • 如果你熟悉 null 合并运算符 (??),你可以将它视为对象方法或属性访问的版本;
  • 简洁的代码,现在可以用新的 nullsafe 运算符链式调用,而不需要条件检查 null;
  • 防止空指针异常, 如果链条中的一个元素失败了,整个链条会中止并认定为 null;
class address {
    public function __construct(
        public ?string $city
    ) {}
}
class user {
    public function __construct(
        public ?address $address
    ) {}
}
// 对象有值的情况
$user = new user(new address("beijing"));
echo $user?->address?->city; // 输出: beijing
// 对象没有值的情况
$userwithoutaddress = new user(null);
echo $userwithoutaddress?->address?->city; // 输出: (null)

1.7 字符串与数字的比较(saner string to number comparisons)

  • php 8 比较数字字符串(numeric string)时,会按数字进行比较。 不是数字字符串时,将数字转化为字符串,按字符串比较。
  • 不过针对这种,我们最好还是用强等,或者类型提前强转,不然当发生问题的时候,可能会有些奇怪;
var_dump(0 == 'foobar'); // false
var_dump(0 == '0');  // true
var_dump(0 === '0'); // false

1.8 内部函数类型错误的一致性(consistent type errors for internal functions)

  • 传递给函数的参数类型不正确时,php 8 会抛出 typeerror;
  • 接收到无效参数时会抛出 valueerror;
// typeerror: strlen(): argument #1 ($str) must be of type string, array given
strlen([]); 
// valueerror: array_chunk(): argument #2 ($length) must be greater than 0
array_chunk([], -1); 

1.9 即时编译 jit

  • php 8 引入了 jit(just-in-time)编译器,这是一个显著的性能优化特性。jit 编译器的目标是提高 php 的执行效率,通过将部分 opcodes 转换为机器代码,以减少执行时间并提升性能。
  • php 8 引入了两个即时编译引擎, tracing jit / function jit ,tracing jit 在两个中更有潜力,它在综合基准测试中显示了三倍的性能, 并在某些长时间运行的程序中显示了 1.5-2 倍的性能改进。 典型的应用性能则和 php 7.4 不相上下;
  • opcache 的作用 为了避免每次代码都需要经过词法分析、语法分析、解释编译,我们可以利用 php 的 opcache 扩展缓存 opcodes 来加快速度;
  • 之前 opcache 扩展可以更快的获取 opcodes 将其直接转到 zend vm ,现在 jit 让它们完全不使用 zend vm 即可运行,zend vm 是用 c 编写的程序,充当 opcodes 和 cpu 之间的一层;
  • jit在opcache优化之后的基础上,结合runtime的信息再次优化,直接生成机器码;
  • jit不是原来opcache优化的替代,是增强;

php 8.1 是 php 语言的一次重大更新。 它包含了许多新功能,包括枚举、只读属性、first-class 可调用语法、纤程、交集类型和性能改进等。

2.1 枚举 (enumerations)

  • 使用枚举而不是一组常量并立即进行验证;
  • 类型安全:枚举强制了类型检查,从而保证了传入的值是定义好的枚举之一,减少了运行时错误的可能性;
  • 避免魔法字符串:使用枚举可以避免重复和可能出错的魔法字符串。这使得代码可维护性更高,不必担心字符串拼写错误等问题。
// 创建枚举
enum status: string
{
    case draft = 'draft';
    case published = 'published';
    case archived = 'archived';
}
// 创建一个方法,接受 status 枚举类型作为参数
function acceptstatus(status $status): void
{
    match ($status) {
        status::draft => print "status is draft" . php_eol,
        status::published => print "status is published". php_eol,
        status::archived => print "status is archived". php_eol,
    };
}
// 使用枚举调用方法
acceptstatus(status::draft);     // 输出 "status is draft"
acceptstatus(status::published); // 输出 "status is published"

2.2 只读属性 (readonly properties)

  • 只读属性不能在初始化后更改,即在为它们分配值后。它们可以用于对值对象和数据传输对象建模;
class geolocation
{
    public readonly float $latitude;
    public readonly float $longitude;
    public function __construct(float $latitude, float $longitude)
    {
        $this->latitude = $latitude;
        $this->longitude = $longitude;
    }
}
// 示例:创建不同的地理位置对象
$nylocation = new geolocation(40.7128, -74.0060);  // 纽约
$lalocation = new geolocation(34.0522, -118.2437); // 洛杉矶
echo "new york location - latitude: " . $nylocation->latitude . ", longitude: " . $nylocation->longitude;
// 输出 "new york location - latitude: 40.7128, longitude: -74.0060"
echo "los angeles location - latitude: " . $lalocation->latitude . ", longitude: " . $lalocation->longitude;
// 输出 "los angeles location - latitude: 34.0522, longitude: -118.2437"

2.3 first-class 可调用语法 (first-class callable syntax)

  • 现在可以获得对任何函数的引用。这统称为 first-class 可调用语法;
  • 那些接受其他函数作为参数的函数,可以更简洁地将方法或函数引用传递给这些高阶函数;
  • first-class 是一项非常强大的功能,通过这个语法,开发者能够更简洁地获取和使用函数或方法引用;
  • 这对编写更清晰、可维护的代码,以及更高效地处理回调函数和高阶函数提供了很大的帮助;
    class stringhelper
    {
      public static function touppercase(string $value): string
      {
          return strtoupper($value);
      }
    }
    // 示例数组
    $words = ["hello", "world", "php8.1"];
    // 使用 first-class callable syntax 将方法引用传递给 array_map
    $uppercasewords = array_map(stringhelper::touppercase(...), $words);
    // 输出结果
    print_r($uppercasewords);

2.4 新的初始化器 (new in initializers)

  • 对象现在可以用作默认参数值、静态变量和全局常量,以及属性参数

    class notifier
    {
      public function notify(string $message): void
      {
          echo "notification: $message" . php_eol;
      }
    }
    class user
    {
      private notifier $notifier;
      public function __construct(
          notifier $notifier = new notifier(),
      ) {
          $this->notifier = $notifier;
      }
      public function notify(string $message): void
      {
          $this->notifier->notify($message);
      }
    }
    $user = new user();
    $user->notify('hello, default notifier');

2.5 纯交集类型 (pure intersection types)

  • 当一个值需要同时满足多个类型约束时,使用交集类型。

    function handle(iterator&countable $value) {
      foreach ($value as $val) {
          echo $val;
      }
      count($value);
    }

    2.6 never 返回类型 (never return type)

  • 使用 never 类型声明的函数或方法表示它不会返回值,并且会抛出异常或通过调用 die()、exit()、trigger_error() 或类似的东西来结束脚本的执行。

function redirect(string $uri): never {
    header('location: ' . $uri);
    exit();
}
function redirecttologinpage(): never {
    redirect('/login');
    echo 'hello';
}

2.7 final 类常量 (final class constants)

  • 可以声明 final 类常量,以禁止它们在子类中被重写
class foo
{
    final public const xx = "foo";
}
class bar extends foo
{
    public const xx = "bar"; // fatal error
}

2.8 显式八进制数字表示法 (explicit octal numeral notation)

  • 现在可以使用显式 0o 前缀表示八进制数
var_dump(0o16 === 16); 
var_dump(0o16 === 14);
var_dump(0o16);

2.9 纤程 (fibers)

fibers 是用于实现轻量级协作并发的基础类型。它们是一种创建可以像生成器一样暂停和恢复的代码块的方法,但可以从堆栈中的任何位置进行。fibers 本身并没有提供并发性,仍然需要一个事件循环。但是,它们允许通过阻塞和非阻塞实现共享相同的 api。
fibers 允许摆脱以前在 promise::then() 或基于生成器的协程中看到的样板代码。库通常会围绕 fiber 构建进一步的抽象,因此无需直接与它们交互。

// 确保你的 php 版本是 8.1 或更高版本,因为 fiber 是 php 8.1 引入的特性
$fiber = new fiber(function() {
    echo "fiber started\n";
    $value = fiber::suspend('fiber paused');
    echo "fiber resumed with value: $value\n";
    return 'fiber ended';
});
// 启动 fiber,并获取它暂停时传递的值
$value = $fiber->start();
echo "main resumed with value: $value\n";
// 恢复 fiber 的执行,并传递一个值
$returnedvalue = $fiber->resume('resuming fiber with this value');
echo "fiber returned with value: $returnedvalue\n";
echo "main ended\n";

2.10 对字符串键控数组的数组解包支持 (array unpacking support for string-keyed arrays)

  • php 以前支持通过扩展运算符在数组内部解包,但前提是数组具有整数键。现在也可以使用字符串键解包数组;
$arraya = ['a' => 1];
$arrayb = ['b' => 2];
$result = ['a' => 0, ...$arraya, ...$arrayb];
var_dump($result);

3.1 只读类

  • readonly 类中的所有属性将自动标记为 readonly,不需要单独声明每个属性;
readonly class blogdata
{
    public string $title;
    public status $status;
    public function __construct(string $title, status $status)
    {
        $this->title = $title;
        $this->status = $status;
    }
}

3.2 析取范式 (dnf)类型

  • dnf 类型允许我们组合 union 和 intersection类型,遵循一个严格规则;
  • 组合并集和交集类型时,交集类型必须用括号进行分组。
    class foo {
      public function bar((a&b)|null $entity) {
          return $entity;
      }
    }

3.3 允许 null、false 和 true 作为独立类型

class falsy
{
    public function alwaysfalse(): false {
        return false;
    }
    public function alwaystrue(): true {
        return true;
    }
    public function alwaysnull(): null {
        return null;
    }
}

3.4 新的“随机”扩展

  • “随机”扩展为随机数生成提供了一个新的面向对象的 api;
  • 这个面向对象的 api 提供了几个类(“引擎”),提供对现代算法的访问,这些算法在对象中存储其状态,以允许多个独立的可播种序列,而不是依赖于使用 mersenne twister 算法的全局种子随机数发生器(rng);
    use random\randomizer;
    $randomizer = new randomizer();
    $randomint = $randomizer->getint(1, 100);
    

var_dump($randomint);


## 3.5 traits 中的常量
- 您不能通过 trait 名称访问常量,但是您可以通过使用 trait 的类访问常量;
```php
trait foo
{
    public const constant = 1;
}
class bar
{
    use foo;
}
var_dump(bar::constant);

3.6 弃用动态属性

  • 动态属性的创建已被弃用,以帮助避免错误和拼写错误;
    class user
    {
      public $name;
    }
    $user = new user();
    $user->last_name = 'doe'; // deprecated notice
    $user = new stdclass();
    $user->last_name = 'doe'; // still allowed

php 8.3 是 php 语言的一次重大更新。 它包含了许多新功能,例如:类常量显式类型、只读属性深拷贝,以及对随机性功能的补充。一如既往,它还包括性能改进、错误修复和常规清理等。

4.1 类型化类常量 (typed class constants)

  • php 8.3 ,增加了类常量的类型定义,如果你给了不符合类型的值,将会抛出 fatal error 致命错误;
  • 当然这不是必须的,你依然可以不参用类型声明;
    class beforefoo
    {
      // php83 之前,可以直接这么定义
      const bar = 'bar'; 
    }
    class foo
    {
      // php83 时,可以给常量也加上类型声明
      const string bar = 'bar'; 
    }
    class errfoo
    {
      // php83 时,你可以给常量加类型声明,但如果错误,将会抛出异常
      // fatal error: cannot use string as value for class constant errfoo::bar of type int
      const int bar = 'bar'; 
    }

4.2 动态获取类常量 (dynamic class constant fetch)

class foo 
{
    const bar = 'bar';
    public $name = '1';
}
$name = 'bar';
// php8.3 之前
echo constant(foo::class . '::' . $name) , php_eol;
// php8.3 现在
echo foo::{$name} , php_eol;
// php8.3 现在 切记给变量带上 {} ,它标识先解析 name 变量,再获取类常量
// 下面是错误用法:fatal error: uncaught error: access to undeclared static property foo::$name
// echo foo::$name;

4.3 新增 #[\override] 属性

  • 通过给方法添加 #[\override] 属性,php 将确保在父类或实现的接口中存在同名的方法。
  • 添加该属性表示明确说明覆盖父方法是有意为之,并且简化了重构过程,因为删除被覆盖的父方法将被检测出来。

4.4 只读属性深拷贝 (deep clone readonly properties)

readonly class people
{
    public function __construct(
        public string $name,
        public string $age,
        public datetime $createdat,
    ) {}
    public function __clone()
    {
        $this->createdat = new datetime(); 
    }
}
$tacks = new people(
    name: 'mochi',
    age: 18,
    createdat: new datetime(),
);
var_dump($tacks);
$nextme = clone $tacks;
// php8.3 之前 fatal error: uncaught error: cannot modify readonly property people::$createdat
// php8.3 可用 在克隆过程中可以重新初始化只读属性
var_dump($nextme);

4.5 新增 json_validate() 函数

/**
 * json 验证 (php83之前)
 *
 * @param string $string
 * @return boolean|string
 */
function jsonvalidate(string $string): bool|string {
    $data = json_decode($string);
    if($data === null || json_last_error() !== json_error_none) {
        return json_last_error_msg();
    } 
    return true;
}
// php8.3
json_validate('{ "test": { "foo": "bar" } }'); // true
json_validate('{ "test": { "foo": "bar" , "test"} }'); // false

4.6 新增 randomizer::getbytesfromstring() 方法

  • 在 php 8.2 中新增的 random 扩展 通过一个新方法生成由特定字节组成的随机字符串。
  • 这种方法可以使开发者更轻松的生成随机的标识符(如域名),以及任意长度的数字字符串。
$randomizer = new \random\randomizer();
$randomdomain = sprintf(
    "%s.example.com",
    $randomizer->getbytesfromstring(
        'abcdefghijklmnopqrstuvwxyz0123456789',
        16,
    ),
);
echo $randomdomain;

4.7 新增 randomizer::getfloat() 和 randomizer::nextfloat() 方法

  • 由于浮点数的精度有限和隐式舍入,生成位于特定区间内的无偏浮点数并非易事,并且常用的用户态380玩彩网官网入口的解决方案可能会生成有偏差的结果或超出请求范围的数字;
  • 所以说官方出手了,还是比自己封装的要高效好用,之后随机浮点数可以来参考这个了
//  新增 getfloat() nextfloat()
$randomizer = new \random\randomizer();
// getfloat($min, $max) 返回之间的浮点数
// closed表示包含该值,表示open排除该值
$temperature = $randomizer->getfloat(
    -89.2,
    56.7,
    \random\intervalboundary::closedclosed,
);
var_dump($temperature);
// nextfloat() 它将为您提供 0 到 1 之间的随机浮点数,其中 1 被排除
var_dump($randomizer->nextfloat());
$chancefortrue = 0.8;
$myboolean = $randomizer->nextfloat() < $chancefortrue;
var_dump($myboolean);

4.8 命令行 linter 支持多个文件

  • 说实话,用 php 也挺久的了,竟然没发现,或者说没用过 -l 选项;
  • 要不是这次看了 php8.3 的新功能380玩彩网380玩彩网官网入口官网入口首页 ,把这个功能明显的列出来,我还真不知道,哈哈哈哈;
$ php -l test1.php test2.php
parse error: syntax error, unexpected end of file in test1.php on line 21
errors parsing test1.php
parse error: syntax error, unexpected token "{", expecting identifier in test2.php on line 5
errors parsing test2.php 

php 8.4 是 php 语言的一次重大更新。 它包含许多新功能,例如属性钩子、不对称可见性、更新的 dom api、性能改进、错误修复和常规清理等。

5.1 属性钩子 (property hooks)

  • 属性钩子提供对计算属性的支持,这些属性可以被 ide 和静态分析工具直接理解,而无需编写可能会失效的 docblock 注释。
  • 此外,它们允许可靠地预处理或后处理值,而无需检查类中是否存在匹配的 getter 或 setter。
class localeclass
{
    public string $languagecode;
    public string $countrycode
    {
        set (string $countrycode) {
            $this->countrycode = strtoupper($countrycode);
        }
    }
    public string $combinedcode
    {
        get => sprintf("%s_%s", $this->languagecode, $this->countrycode);
        set (string $value) {
            [$this->languagecode, $this->countrycode] = explode('_', $value, 2);
        }
    }
    public function __construct(string $languagecode, string $countrycode)
    {
        $this->languagecode = $languagecode;
        $this->countrycode = $countrycode;
    }
}
$brazilianportuguese = new localeclass('pt', 'br');
var_dump($brazilianportuguese->countrycode); // br
var_dump($brazilianportuguese->combinedcode); // pt_br

5.2 不对称可见性 (asymmetric visibility)

  • 现在可以独立地控制写入属性的作用域和读取属性的作用域,减少了需要编写繁琐的 getter 方法来公开属性值而不允许从类外部修改属性的需求

  • 该类 phpversion 定义了一个私有版本属性,并通过公共方法访问该属性。

  • 提供 increment 方法递增次版本号。通过正确的保护和访问控制实现属性的只读特性。

  • 并保证了版本属性只能通过类内部的方法被修改,外部只能读取。

    class phpversion{
      public private(set) string $version = '8.4';
      public function increment(): void{
          [$major, $minor] = explode('.', $this->version);
          $minor;
          $this->version = "{$major}.{$minor}";
      }
    }
    // 使用示例
    $obj = new phpversion();
    $obj->increment();
    var_dump($obj->getversion()); // 输出 string(3) "8.5"

5.3 #[\deprecated] 属性

  • 新的 #[\deprecated] 属性使 php 的现有弃用机制可用于用户定义的函数、方法和类常量

5.4 新的 ext-dom 功能和 html5 支持

  • 新的 dom api 包括符合标准的支持,用于解析 html5 文档,修复了 dom 功能行为中的几个长期存在的规范性错误,并添加了几个函数,使处理文档更加方便
  • 新的 dom api 可以在 dom 命名空间中使用。使用新的 dom api 可以使用 dom\htmldocument 和 dom\xmldocument 类创建文档

5.5 bcmath 的对象 api (object api for bcmath)

  • 新的 bcmath\number 对象使在处理任意精度数字时可以使用面向对象的方式和标准的数学运算符。
  • 这些对象是不可变的,并实现了 stringable 接口,因此可以在字符串上下文中使用,如 echo $num。
use bcmath\number;
$num1 = new number('0.12345');
$num2 = new number('2');
$result = $num1  $num2;
echo $result; // '2.12345'
var_dump($num1 > $num2); // false

5.6 新的 array_*() 函数

  • 使用 array_find 查找第一个以字母 ‘c’ 开头的元素。
  • 传入的回调函数是一个静态匿名函数 static fn (string $value): bool => str_starts_with($value, ‘c’),它使用 str_starts_with 函数检查字符串是否以 c 开头。
    $animal = array_find(
      ['dog', 'cat', 'cow', 'duck', 'goose'],
      static fn (string $value): bool => str_starts_with($value, 'c'),
    );
    

var_dump($animal); // string(3) “cat”

## 5.7 pdo 驱动程序特定子类
## 5.8 new myclass()->method() 不需要括号
- 现在可以在不使用括号包裹 new 表达式的情况下访问新实例化对象的属性和方法。
```php
class phpversion
{
    public function getversion(): string
    {
        return 'php 8.4';
    }
}
var_dump(new phpversion()->getversion());

6.1 开国元老级别

  • rasmus lerdorf(拉斯马斯・勒德尔夫),php 语言之父:1995年首次发布 php。在多家知名企业担任技术领导角色,包括 yahoo! 和 wepay。 负责开发和维护 yahoo! 的核心基础设施。
  • andi gutmans,创立 zend technologies:与 zeev suraski 一起创立了 zend technologies,用于 php 的商业化应用和性能优化。通过开发 php 3 和 zend engine,对 php 4 和 php 5 的推进起到关键作用,并参与管理 php 7 的开发。目前是 google 数据库工程的副总裁。
  • zeev suraski,与 andi gutmans 一起创建了 php 3,开发了 zend engine,并推动了 php 4 和 php 5 的发展。 职业经历:曾为 zend technologies 的首席技术官,并且自 2019 年起担任 strattic 的首席技术官。
  • zend 这个名字是他们的名字 zeev 和 andi 的合成词。是的,没错,每次你输入的 php -v 后面显示 zend 引擎就是这个。

6.2 国内的开发者

6.2.1 惠新宸

  • 人称鸟哥
  • 博客 风雪之隅
  • yaf, yar, yac 等扩展的作者,php7 的主要贡献者。确实 yaf 这个作为 php api 框架非常轻便高效。

6.2.2 韩天峰

  • swoole开源项目创始人,php语言官方扩展开发组成员

6.3 国外的开发者

6.4 关注的 php 博主

6.5 关注的活跃php项目

6.6 关注的站点

php
本作品采用《cc 协议》,转载必须注明作者和本文链接
明天我们吃什么 悲哀藏在现实中 tacks
讨论数量: 9

至今不喜欢注解

1周前
1周前
tacks (楼主) 5天前

在模仿java的道路上越走越偏, 最终将消失在互联网. :joy:

6天前
tacks (楼主) 5天前
tuesdays (作者) 4天前

极简主义 golang 加各种语法 真实蛋疼的

6天前
tacks (楼主) 5天前
tuesdays 4天前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
网站地图