我想用这样的数组命名方法
class MyClass {
private $_array = array();
public function __construct($array) {
$this->_array = $array; //this works!
}
//now, what i'm trying to do is:
foreach ($this->_array AS $methodName) {
public function $methodName.() {
//do something
}
}
}
这样做的正确方法是什么?
答案 0 :(得分:0)
当你使用类并想要类似动态方法的东西时 - 我认为神奇的方法__call是最好的方法。
你可以很容易地做到:
class MyClass {
private $_array = array();
public function __construct($array) {
$this->_array = $array; //this works!
}
public function __call($method, $args) {
if(in_array($method, $this->_array)){
print "Method $method called\n";
//or you can make like this: return call_user_func_array($method, $args);
}
}
}
$obj = new MyClass(array("one","two"));
$obj->two(); // OUTPUT: Method two called