avantar / 只读属性
一个小特性,用于阻止类属性的setter。
0.1.1
2021-01-03 19:27 UTC
Requires
- php: >=5.5
Requires (Dev)
- phpunit/phpunit: ^9.5
README
一个小特性,用于阻止类属性的setter。
如何使用
在类定义中声明使用ReadableOnlyProperties
特性。
<?php class User { use ReadableOnlyProperties; private string $name; private int $age; public function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } }
在创建用户类的新实例后,可以直接访问其私有属性。
$user = new User('Chris', 35); echo $user->name;
这将输出Chris
字符串。但当你尝试设置name或age属性的新值时
$user->name = 'Charlie';
将抛出异常
Fatal error: Uncaught Exception: Property name is read only in /Users/avantar/Projects/readable-only-properties/ReadableOnlyProperties.php:18 Stack trace: #0 /Users/avantar/Projects/readable-only-properties/ReadableOnlyProperties.php(42): User->__set('name', 'Charlie') #1 {main} thrown in /Users/avantar/Projects/readable-only-properties/ReadableOnlyProperties.php on line 18