使用数组定义类中方法的名称

VNI*_*VNI 5 arrays methods class

我想用这样的数组命名方法

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

Ent*_*iff 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 
Run Code Online (Sandbox Code Playgroud)