rakshazi / get-set-go-improved
Requires
- php: >=5.4.0
This package is auto-updated.
Last update: 2022-02-01 12:57:28 UTC
README
此仓库不再维护,请使用 GetSetTrait 代替。
A dynamic setter-getter library for PHP 5.4+.
You can use methods like setFoo('bar')
and getFoo()
, which you DON'T have to create (in your class). GetSetGo will make these methods work for you automatically as long as you have a $foo
property in your class.
It makes use of Traits, so using
it is super simple, you don't have to extend any class, as you can extend a single class only, we don't force you to use ours. You can restrict to only getter only or you can specify a Type for property using annotations.
安装
GetSetGo 使用 Composer 来简化流程。
学习如何使用 Composer 并将其添加到 require(在您的 composer.json 中)
"rakshazi/get-set-go-improved": "dev-master"
Library on Packagist.
用法
只需将此添加到您的类中
use \GetSetGo\SetterGetter;
示例
Class MyClass{ use \GetSetGo\SetterGetter; protected $foo; }
现在可以这样使用它
$myClass = new MyClass; $myClass->setFoo('bar'); echo $myClass->getFoo();
基本上就是这样。
限制 Getter 或 Setter 或两者
如果您想禁用 setter、getter 或两者,可以在类属性中使用注释变量 @setter
和 @getter
。
/** * We can't use setSomeProperty() anymore. * * @var * @setter false */ protected $someProperty;
/** * We can't use getSomeProperty() anymore. * * @var \stdClass * @getter false */ protected $someProperty;
/** * We can't use setSomeProperty() or getSomeProperty(). * * @getter false * @setter false */ protected $someProperty;
强制指定类型或类
您可以使用 @var
注释变量为属性指定类型,这样 setter 将只接受此类型的值,否则将抛出异常。以下代码将类似于 public function setSomeProperty(stdClass $value){}
/** * Should be an instance of stdClass only. * * @var \stdClass */ protected $shouldBeStdClass;
/** * Should be an array only. * * @var Array */ protected $shouldBeArray;
/** * Should be a string only * * @var String */ protected $shouldBeString;
/** * Should be a number only. * * @var Number */ protected $shouldBeNumber;
/** * Should be an object only. * * @var Object */ protected $shouldBeObject;
注意
GetSetGo 假设您使用正确的 camelCase。因此,请将属性命名为 $pdoInstance
(而不是 $PDOInstance
)并调用 setPdoInstance()
方法。