【问题标题】:php automated setter and getterphp 自动设置器和获取器
【发布时间】:2012-01-05 13:00:08
【问题描述】:

我正在尝试为 php 对象实现一些自动化的 getter 和 setter。

我的目标是为每个属性自动设置getProperty()setProperty(value) 方法,这样如果没有为属性实现该方法,脚本将简单地设置或获取值。

一个例子,让我自己清楚:

class Foo {
    public $Bar;
}

$A = new A();
$A->setBar("bar");
$A->getBar(); // -> output "bar"

class Foo {
    public $Bar;
    public function setBar($bar) { $Bar = $bar; }
    public function getBar($bar) { return 'the value is: ' . $bar; }
}

$A = new A();
$A->setBar("bar");
$A->getBar(); // -> output "the value is: bar"

关于如何做到这一点的任何想法/提示?

【问题讨论】:

  • 只是实地考察:您如何解析文档并使用输出编写器为每个找到的属性编写 setter 和 getter。我会进一步建议搜索已经可以做到这一点的框架。 其他平台甚至可以通过自动持久性来做到这一点(例如用于 Java 平台的 Grails)

标签: php oop setter getter


【解决方案1】:

如果您想模拟任意属性的getXysetXy 函数,请使用魔术__call 包装器:

function __call($method, $params) {

     $var = lcfirst(substr($method, 3));

     if (strncasecmp($method, "get", 3) === 0) {
         return $this->$var;
     }
     if (strncasecmp($method, "set", 3) === 0) {
         $this->$var = $params[0];
     }
}

这将是一次做一些有用的事情的好机会,通过添加一个类型映射或任何东西。否则建议一起避开getters and setters

【讨论】:

  • 一些修复 strncasecmp($method, "set", 3) === 0 // same thing for the prev$var = lcfirst(substr($method, 3)); // e.g. for camelcase
  • @th3n3rd 你的链接失效了
  • @turibe 我没有发布任何链接,我不确定你指的是什么。
  • @th3n3rd 该评论是给我/答案的(并且链接链接已修复:internat-archive 等)
【解决方案2】:

阅读magic functions of php,您可以根据需要使用__get and __set函数

read this

【讨论】:

  • 不是这样。我需要相反的技巧。 __get__set 在属性本身不存在时使用
  • 他确实告诉过你要阅读魔法函数。检查__call 魔术函数的作用。
猜你喜欢
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多