是否可以从 PHP 中的数组值自动生成 Getter/Setter?

发布于 2024-09-04 17:58:06 字数 766 浏览 9 评论 0原文

所以我有几个数组

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝不服输 2024-09-11 17:58:06

您可以使用 __call() 来调用动态方法。所以:就

class Wrapper {
  private $properties;

  public function __construct(array $names) {
    $this->properties = array_combine(array_keys($names),
      array_fill(0, count($names), null));
  }

  public function __call($name, $args) {
    if (preg_match('!(get|set)(\w+)!', $name, $match)) {
      $prop = lcfirst($match[2]);
      if ($match[1] == 'get') {
        if (count($args) != 0) {
          throw new Exception("Method '$name' expected 0 arguments, got " . count($args));
        }
        return $properties[$prop];
      } else {
        if (count($args) != 1) {
          throw new Exception("Method '$name' expected 1 argument, got " . count($args));
        }
        $properties[$prop] = $args[0];
      }
    } else {
      throw new Exception("Unknown method $name");
    }
  }
}

我个人而言,我不会在 PHP 中使用 getter 和 setter。请改用特殊方法 __get()__set() 并将这些动态属性视为对象属性,而不是添加(很可能是不必要的)方法包装器。

编辑:澄清一下,当您调用不存在或不可访问的对象中的方法时,将调用__call()。所以:

$wrapper = new Wrapper($array_1);
$wrapper->setOne("foo");
echo $wrapper->getOne(); // foo
$wrapper->getAbc(); // exception, property doesn't exist

这里使用__call()来破译方法名称。如果它符合 get 或 set 后跟属性名称(来自初始数组)的模式,那么它会按预期工作,否则会引发异常。您当然可以按照您希望的方式更改此行为。

有关这些内容的更详细说明,请参阅 PHP 手册中的重载”魔术”的方法。

You can use __call() to invoke dynamic methods. So:

class Wrapper {
  private $properties;

  public function __construct(array $names) {
    $this->properties = array_combine(array_keys($names),
      array_fill(0, count($names), null));
  }

  public function __call($name, $args) {
    if (preg_match('!(get|set)(\w+)!', $name, $match)) {
      $prop = lcfirst($match[2]);
      if ($match[1] == 'get') {
        if (count($args) != 0) {
          throw new Exception("Method '$name' expected 0 arguments, got " . count($args));
        }
        return $properties[$prop];
      } else {
        if (count($args) != 1) {
          throw new Exception("Method '$name' expected 1 argument, got " . count($args));
        }
        $properties[$prop] = $args[0];
      }
    } else {
      throw new Exception("Unknown method $name");
    }
  }
}

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:

$wrapper = new Wrapper($array_1);
$wrapper->setOne("foo");
echo $wrapper->getOne(); // foo
$wrapper->getAbc(); // exception, property doesn't exist

__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.

墨离汐 2024-09-11 17:58:06

您可以使用 __call() (或 __set() && __get()),但它们有一些开销。

You can use __call() (or __set() && __get()), but they have some overhead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文