ajbdev / php-struct
PHP 结构体
dev-master
2015-06-29 16:39 UTC
Requires
- php: >=7
This package is not auto-updated.
Last update: 2024-09-14 17:58:46 UTC
README
受 Go 语言启发的 PHP7 结构体
用法
struct('User', [ 'name' => 'string', 'age' => 'int', 'active' => 'bool', ]); $user = new User(); $user['name'] = 'Andy'; $user['age'] = 13; $user['active'] = true; $user['email'] = 'andybaird@gmail.com'; // Fatal error: Uncaught InvalidArgumentException: Struct does not contain property `email` $user['age'] = '22'; // Fatal error: Uncaught TypeException: Argument 1 passed to User::set_age() must be of the type integer, string given
关闭严格的类型检查,并允许通过简单调用将变量转换为类型
Struct\Struct::$strict = false; $user['age'] = '22'; var_dump($user['age']); // int(22)
在底层,结构体只是实现 ArrayAccess 和 Iterable 的类,它们在运行时生成。它们为所有字段生成getter和setter,从而允许它们进行类型检查。
从数组填充结构体
$row = $db->fetchArray('select * from user where id=1'); $user->fromArray($row);
您可以通过为它们提供自己的方法来进一步扩展结构体。
struct('User', [ 'firstName' => 'string', 'lastName' => 'string', 'active' => 'bool', 'age' => 'int' ],[ 'fullName' => function() { return $this['firstName'] . ' ' . $this['lastName']; } ]); $user['firstName'] = 'Andy'; $user['lastName'] = 'Baird'; echo $user->fullName(); // Andy Baird
简单地添加魔法方法
struct('User', [ 'firstName' => 'string', 'lastName' => 'string', 'active' => 'bool', 'age' => 'int' ],[ '__toString' => function() { return $this['firstName'] . ' ' . $this['lastName'] . ' is a ' . $this['age'] . ' year old ' . ($this['active'] ? 'active' : 'inactive') . ' user'; } ]); echo $user; // Andy Baird is a 13 year old inactive user
但是...为什么?
仅仅是为了我的实验。我很乐意看到结构体被实现为PHP的核心特性,因为我认为它们非常适合更程序化或函数式的编程风格。