作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我需要一个在我的每个公共(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/
我是一名优秀的程序员,十分优秀!