php - 如何在 PHP 中的所有公共(public)方法之前调用方法?

标签 php class

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

公共(public)方法有没有像__call这样的方法?

我想在我的 setter 方法之前删除所有参数。

最佳答案

不,没有像__call 这样的公共(public)方法机制。但是 __call() 已经是您要找的东西了。

我会使用 __call 定义一个“伪公共(public)”接口(interface):

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

关于php - 如何在 PHP 中的所有公共(public)方法之前调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16468427/

相关文章:

c++ - 从静态函数访问静态变量

class - PowerShell 5 和类 - 无法将 "X"类型的 "X"值转换为 "X"类型

python - 添加分数类 python

php - 使用 php 从 mysql 中的 3 个表创建下载脚本

php - Google Visualization API 中的逗号分隔数据

java - 错误 : Generic Array Creation

python - 将不同的变量分配给不同的类

php - 在 codeigniter 中转换复杂的 JOIN 查询

php - 文本区域的富文本编辑器

php mysql从日期字段中查找早于一天的行