我需要一个在我的每个公共方法之前运行的方法。
有没有像 __call 这样的公共方法的方法?
我想在我的 setter 方法之前修剪所有参数。
No, there is no mechanism like __call
for public methods. But __call()
is already what you are looking for.
I would define a "pseudo public" interface using __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);
}
}
If you try the example:
$a = new A();
$a->setValue("foo");
... you'll get the following output:
Attempting to set value to foo