是否可以从 PHP 中的数组值自动生成 Getter/Setter?
所以我有几个数组
$array_1 = Array('one','two','three');
$array_2 = Array('red','blue','green');
是否有一种动态方法来为具有单值条目的数组创建 Setter 和 Getter?
所以这个类会是这样的:
class xFromArray() {
}
所以上面如果我传递 $array_1 它会生成这样的东西:
private $one;
setOne($x) {
$one = $x;
}
getOne() {
return $one;
}
如果我传递 $array_2 它会生成这样的东西:
private $red;
setRed($x) {
$red = $x;
}
getRed() {
return $red;
}
所以我会这样称呼它? (我最好的猜测,但似乎这行不通)
$xFromArray = new xFromArray;
foreach($array_1 as $key=>$data) {
$xFromArray->create_function(set.ucfirst($data)($data));
echo $xFromArray->create_function(get.ucfirst($data));
}
So I have a couple of arrays
$array_1 = Array('one','two','three');
$array_2 = Array('red','blue','green');
Is there a dynamic way to create the Setters and Getters for an array with single value entries?
So the class would be something like:
class xFromArray() {
}
So the above if I passed $array_1 it would generate something like this:
private $one;
setOne($x) {
$one = $x;
}
getOne() {
return $one;
}
if I passed $array_2 it would generate something like this:
private $red;
setRed($x) {
$red = $x;
}
getRed() {
return $red;
}
So I would call it somehow like this? (My best guess but doesn't seem that this would work)
$xFromArray = new xFromArray;
foreach($array_1 as $key=>$data) {
$xFromArray->create_function(set.ucfirst($data)($data));
echo $xFromArray->create_function(get.ucfirst($data));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 __call() 来调用动态方法。所以:就
我个人而言,我不会在 PHP 中使用 getter 和 setter。请改用特殊方法
__get()
和__set()
并将这些动态属性视为对象属性,而不是添加(很可能是不必要的)方法包装器。编辑:澄清一下,当您调用不存在或不可访问的对象中的方法时,将调用
__call()
。所以:这里使用
__call()
来破译方法名称。如果它符合 get 或 set 后跟属性名称(来自初始数组)的模式,那么它会按预期工作,否则会引发异常。您当然可以按照您希望的方式更改此行为。有关这些内容的更详细说明,请参阅 PHP 手册中的重载”魔术”的方法。
You can use
__call()
to invoke dynamic methods. So:Personally I wouldn't go the route of using getters and setters in PHP. Use the special methods
__get()
and__set()
instead and treat these dynamic properties as object properties rather than adding a (most likely unnecessary) method wrapper.Edit: to clarify,
__call()
is invoked when you call an method in an object that either doesn't exist or is inaccessible. So:__call()
is used here to decipher the method name. If it fits the pattern of get or set followed by a property name (from the initial array) then it works as expected, otherwise it throws an exception. You can of course change this behaviour any way you wish.See Overloading from the PHP manual for a more detailed explanation of these "magic" methods.
您可以使用 __call() (或 __set() && __get()),但它们有一些开销。
You can use __call() (or __set() && __get()), but they have some overhead.