phpgt / propfunc
属性访问器和修改器函数。
v1.0.1
2021-03-23 12:46 UTC
Requires
- php: >=8.0
Requires (Dev)
- phpstan/phpstan: >=0.12
- phpunit/phpunit: >=9.3
This package is auto-updated.
Last update: 2024-09-10 08:32:18 UTC
README
属性访问器和修改器通常被称为“获取器”和“设置器”函数。这个库使用 PHP的魔术方法 来轻松连接外部作为普通属性暴露的获取器和设置器函数,通过 MagicProp
特性。
为什么?这种功能当然可以被视为一种黑客手段,但有时黑客手段是必要的。具体来说,PHP.Gt正在实现 PHP中的DOM标准,这需要某些属性具有“实时”或“只读”功能,而这只能通过魔术 __get 和 __set 函数实现。这个库简单地保存了其他需要它的存储库可重用的行为。
示例用法:访问时计算的可读属性
下面是表示时间中一天的 Day
类
use Gt\PropFunc\MagicProp; /** * @property-read bool $future True if the day is in the future * @property-read int $daysApart Days between now and this day */ class Day { use MagicProp; public function __construct( private DateTimeInterface $dateTime ) {} // Expose the "dateTime" private property with read-only access: private function __prop_get_dateTime():DateTimeInterface { return $this->dateTime; } // Expose the "future" calculated property with read-only access: private function __prop_get_future():bool { $now = new DateTime(); return $now < $this->dateTime; } // Expose the "daysApart" calculated property with read-only access: private function __prop_get_daysApart():int { $now = new DateTime(); $diff = $now->diff($this->dateTime); return $diff->days; } }
下面是使用 Day
类的代码。它可以访问属性,但不能修改它们。
$day = new Day($dateTime); echo "Day is $day->diff days in the "; echo $day->future ? "future" : "past"; echo PHP_EOL; $day->diff = 10; echo "Exception thrown on line above!";
用法
- 只读属性 - 如上例所示,属性可以是只读的。此功能 即将添加到PHP语言,但没有定义访问器逻辑的能力。
- 实时属性 - 如果属性的值需要根据某些条件更新,则需要获取器函数。
- 属性验证 - 如果属性值不能仅通过其类型本身进行验证,则可以使用设置器函数来确保值符合验证标准。