PHP类:写对象内的函数?

问题描述:

我不知道下面这个是否可能出现在php类对象中,就像我在javascript(jquery)中那样。PHP类:写对象内的函数?

jQuery中,我会做,

(function($){ 


    var methods = { 

    init : function(options) { 
     // I write the function here... 

    }, 

    hello : function(options) { 

      // I write the function here... 
     } 
    } 

    $.fn.myplugin = function(method) { 

    if (methods[method]) { 
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
     } else if (typeof method === 'object' || ! method) { 
      return methods.init.apply(this, arguments); 
     } else { 
      $.error('Method ' + method + ' does not exist.'); 
     } 
     return this; 
    }; 
})(jQuery); 

所以,当我想打电话给内部myplugin一个功能,我只是这样做,

$.fn.myplugin("hello"); 

所以,我认为,有可能是当你来写一个课程的时候,一种在php中这样做的方法?

$method = (object)array(
"init" => function() { 
    // I write the function here... 
}, 
"hello" => function() { 
// I write the function here...  

} 
); 

编辑:

难道是这样一类?

class ClassName { 

    public function __construct(){ 
    // 
    } 

    public function method_1(){ 

     $method = (object)array(

      "init" => function() { 
       // I write the function here... 
      }, 
      "hello" => function() { 
      // I write the function here...  

      } 
     ); 

    } 


    public function method_2(){ 

     $method = (object)array(

      "init" => function() { 
       // I write the function here... 
      }, 
      "hello" => function() { 
      // I write the function here...  

      } 
     ); 

    } 

} 

$.fn.myplugin功能非常相似,在PHP中__call()神奇的功能。但是,你必须在一个类来定义它和仿效的逻辑:

class Example { 
    private $methods; 

    public function __construct() { 
     $methods = array(); 
     $methods['init'] = function() {}; 
     $methods['hello'] = function() {}; 
    } 

    public function __call($name, $arguments) { 
     if(isset($methods[$name])) { 
      call_user_func_array($methods[$name], $arguments); 
     } else if($arguments[0] instanceof Closure) { 
      // We were passed an anonymous function, I actually don't think this is possible, you'd have to pass it in as an argument 
      call_user_func_array($methods['init'], $arguments); 
     } else { 
      throw new Exception("Method " . $name . " does not exist"); 
     } 
    } 
} 

然后,你会怎么做:

$obj = new Example(); 
$obj->hello(); 

这不是测试,但希望这是一个开始。

+0

谢谢,但不应该是'$ obj = new例子();'和'public function Example(){}'? – laukok

+1

@lauthiamkok - 因此“没有测试”......我会做出一些小的改变。 – nickb

class ClassName { 

    public function __construct(){ 
    //this is your init 
    } 

    public function hello(){ 
    //write your function here 
    } 

} 

是你会怎么写呢

然后

$a = new ClassName() 

$a->hello(); 

叫它

+0

这是我已经知道的基本类。 – laukok

+0

你想要一个匿名类吗? – exussum

+0

也许但是什么是匿名类?从来没有做过。一个匿名类有什么好处? – laukok

PHP支持闭幕(匿名函数) 类似的jQuery看看

function x(callable $c){ 
    $c(); 
} 

然后用

x(function(){ 
    echo 'Hello World'; 
});