PHP类:在对象内编写函数?

时间:2013-08-02 15:04:09

标签: php oop stdclass php-5.4

我想知道下面是否可以在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...    

            } 
        );

    }

}

3 个答案:

答案 0 :(得分:2)

您的$.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();

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

答案 1 :(得分:1)

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

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

然后使用

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

答案 2 :(得分:0)

class ClassName {

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

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

}

是你怎么写的

然后

$a =  new ClassName()

$a->hello();

来称呼它