对象属性现在可以其 get 和 set 操作中关联相关的附加逻辑。根据用法,这可能会也可能不会使属性变为虚拟属性,即该属性根本没有实际的存储值。
<?php
class Person
{
// “虚拟”属性,可能无法明确设置。
public string $fullName {
get => $this->firstName . ' ' . $this->lastName;
}
// 所有的写入操作都会经过这个挂钩,结果就是写入的内容。
// 读取访问正常。
public string $firstName {
set => ucfirst(strtolower($value));
}
// 所有的写入操作都会经过这个挂钩,它必须写入支持值本身。
// 读取访问正常。
public string $lastName {
set {
if (strlen($value) < 2) {
throw new \InvalidArgumentException('Too short');
}
$this->lastName = $value;
}
}
}
$p = new Person();
$p->firstName = 'peter';
print $p->firstName; // 打印“Peter”
$p->lastName = 'Peterson';
print $p->fullName; // 打印“Peter Peterson”
不对称属性可见性
现在可以将对象属性的 set 可见性和 get 可见性分开控制。
<?php
class Example
{
// 第一个可见性修饰符控制 get 可见性,第二个修饰符控制 set 可见性。
// The get-visibility must not be narrower than set-visibility.
public protected(set) string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
class PhpVersion
{
#[\Deprecated(
message: "use PhpVersion::getVersion() instead",
since: "8.4",
)]
public function getPhpVersion(): string
{
return $this->getVersion();
}
public function getVersion(): string
{
return '8.4';
}
}
$phpVersion = new PhpVersion();
// Deprecated: Method PhpVersion::getPhpVersion() is deprecated since 8.4, use PhpVersion::getVersion() instead
echo $phpVersion->getPhpVersion();
新的 ext-dom 功能和 HTML5 支持
新的 DOM API 包括符合标准的支持,用于解析 HTML5 文档,修复了 DOM 功能行为中的几个长期存在的规范性错误,并添加了几个函数,使处理文档更加方便。
新的 DOM API 可以在 Dom 命名空间中使用。使用新的 DOM API 可以使用 Dom\HTMLDocument 和 Dom\XMLDocument 类创建文档。
$dom = Dom\HTMLDocument::createFromString(
<<<HTML
<main>
<article>PHP 8.4 is a feature-rich release!</article>
<article class="featured">PHP 8.4 adds new DOM classes that are spec-compliant, keeping the old ones for compatibility.</article>
</main>
HTML,
LIBXML_NOERROR,
);
$node = $dom->querySelector('main > article:last-child');
var_dump($node->classList->contains("featured")); // bool(true)