gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:07:27 25 4
gpt4 key购买 nike

我需要一个在我的每个公共(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com