2013-08-02 2882 views
1

我不知道下面這個是否可能出現在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...  

      } 
     ); 

    } 

} 

回答

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(); 

這不是測試,但希望這是一個開始。

+0

謝謝,但不應該是'$ obj = new例子();'和'public function Example(){}'? – laukok

+1

@lauthiamkok - 因此「沒有測試」......我會做出一些小的改變。 – nickb

0
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

1

PHP支持閉幕(匿名函數) 類似的jQuery看看

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

然後用

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