37

PHP では、次のようなことを行うことができます。

myFunction( MyClass::staticMethod );

「myFunction」が静的メソッドへの参照を持ち、それを呼び出すことができるようにします。やってみると「Undefined class constant」(PHP 5.3)のエラーが出るので直接は無理だと思いますが、似たようなことをする方法はありますか?これまでに管理した中で最も近いのは、「関数」を文字列として渡し、call_user_func() を使用することです。

4

8 に答える 8

36

これを行う 'php の方法' は、is_callablecall_user_funcで使用されるまったく同じ構文を使用することです。

これは、あなたの方法が存在に対して「中立」であることを意味します

  • 標準関数名
  • 静的クラス メソッド
  • インスタンスメソッド
  • 閉鎖

静的メソッドの場合、これは次のように渡す必要があることを意味します。

myFunction( [ 'MyClass', 'staticMethod'] );

または、まだ PHP 5.4 を実行していない場合:

myFunction( array( 'MyClass', 'staticMethod') );
于 2012-07-25T18:07:24.007 に答える
11

Since you've already mentioned that call_user_func() has been used and you're not interested in a solution with that or ones that are passing the static function as a string, here is an alternative: using anonymous functions as a wrapper to the static function.

function myFunction( $method ) {
    $method();
}

myFunction( function() { return MyClass::staticMethod(); } );

I wouldn't recommend doing this, as I think the call_user_func() method is more concise.

于 2012-07-25T18:06:56.167 に答える
9

文字列を避けたい場合は、次の構文を使用できます。

myFunction( function(){ return MyClass::staticMethod(); } );

少し冗長ですが、静的に分析できるという利点があります。つまり、IDE は静的関数の名前のエラーを簡単に指摘できます。

于 2012-07-25T20:16:44.453 に答える
5

完全な例を挙げてみましょう...

次のように呼び出します。

myFunction('Namespace\\MyClass', 'staticMethod');

またはこのように(渡したい引数がある場合):

myFunction('Namespace\\MyClass', 'staticMethod', array($arg1, $arg2, $arg3));

そして、この呼び出しを受け取る関数:

public static function myFunction($class, $method, $args = array())
{
    if (is_callable($class, $method)) {
        return call_user_func_array(array($class, $method), $args);
    }
    else {
        throw new Exception('Undefined method - ' . $class . '::' . $method);
    }
}

同様の手法は、phpのDecorator パターンでも一般的に使用されています。

于 2014-09-19T21:18:46.470 に答える
1

これにより、出力の最初の呼び出しに6、2番目の呼び出しに9が表示されます。

$staticmethod1 = function ($max)
{
    return $max*2;
};

$staticmethod2 = function ($max)
{
    return $max*$max;
};

function myfunction($x){
    echo $x(3);
}

myfunction($staticmethod1);
myfunction($staticmethod2);
于 2012-07-25T19:43:58.143 に答える
0

PHP 7.4 以降、これは便利で IDE フレンドリーです。

myFunction(fn() => MyClass::staticMethod());
于 2020-01-02T11:57:34.613 に答える