如何在PHP中的所有公共方法之前调用方法?

时间:2013-05-09 18:19:29

标签: php class

我需要一个在每个公共方法之前运行的方法。

公共方法是否有类似__call的方法?

我想在我的setter方法之前修剪所有参数。

1 个答案:

答案 0 :(得分:0)

不,公共方法没有类似__call的机制。但是__call()已经是您正在寻找的。

我会定义一个"伪公共"界面使用__call

class A {

    protected $value;

    /**
     * Enables caller to call a defined set of protected setters.
     * In this case just "setValue".
     */
    public function __call($name, $args) {
        // Simplified code, for brevity 
        if($name === "setValue") {
            $propertyName = str_replace("set", "", $name);
        }

        // The desired method that should be called before the setter
        $value = $this->doSomethingWith($propertyName, $args[0]);

        // Call *real* setter, which is protected
        $this->{"set$propertyName"}($value);
    }

    /**
     * *Real*, protected setter
     */
    protected function setValue($val) {
        // What about validate($val); ? ;)
        $this->value = $val;
    }

    /**
     * The method that should be called
     */
    protected function doSomethingWith($name, $value) {
         echo "Attempting to set " . lcfirst($name) . " to $value";
         return trim($value);
    }
}

如果你试试这个例子:

$a = new A();
$a->setValue("foo");

...您将获得以下输出:

Attempting to set value to foo