1

我想知道这在 php 类对象中是否可能,就像我在 javascript (jquery) 中所做的那样。

在 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...    

            } 
        );

    }

}
4

3 回答 3

2

您的函数与PHP$.fn.myplugin中的魔术函数非常相似。__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();

它没有经过测试,但希望这是一个开始。

于 2013-08-02T15:54:36.457 回答
1

PHP 支持 Closure(匿名函数)类似于 jQuery 看看

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

然后使用

x(function(){
     echo 'Hello World';
});
于 2013-08-02T15:25:44.103 回答
0
class ClassName {

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

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

}

你会怎么写

然后

$a =  new ClassName()

$a->hello();

叫它

于 2013-08-02T15:05:57.470 回答