PHP的自动安装和获取 [英] php automated setter and getter

查看:90
本文介绍了PHP的自动安装和获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为php对象实现一些自动的getter和setter方法.

I'm trying to implement some automated getter and setter for php objects.

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

My target is to automatically have for each properties the methods getProperty() and setProperty(value), that way if the method is not implemented for a property the script will simply set or get the value.

一个例子,以使自己清楚:

An example, to make myself clear:

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"

关于如何实现此目标的任何想法/提示?

Any idea/hints on how to accomplish this?

推荐答案

如果要为任意属性模拟getXysetXy函数,请使用魔术

If you want to simulate the getXy and setXy functions for arbitrary properties, then use the magic __call wrapper:

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];
     }
}

这将是一次很好的机会,可以通过添加类型图或其他任何东西来做一次有用的事情.否则,避免使用一起使用.

This would be a good opportunity to do something useful for once, by adding a typemap or anything. Otherwise eschewing getters and setters alltogether might be advisable.

这篇关于PHP的自动安装和获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆