phpのmethod_exists()関数で自分自身にメソッドがあるかどうかを調べるには

2013/01/23

P1190056.JPG

method_exists()関数は、第1引数にオブジェクトのインスタンスまたはクラス名、第2引数にメソッド名を指定するのだけれど、クラス内で自分自身にメソッドがあるかどうかを調べる方法がよく分からなかったので整理した。

引数に使えるのは以下。

  • 名前そのもの
  • __CLASS__
  • get_class()
  • get_called_class()

例えばこんな感じ。

class foo
{
    public static function bar1() {
        if (method_exists('foo', 'bar1')) {
            echo __CLASS__ . "::bar1()\n";
        }
    }

    public static function bar2() {
        if (method_exists(__CLASS__, 'bar2')) {
            echo __CLASS__ . "::bar2()\n";
        }
    }

    public static function bar3() {
        if (method_exists(get_class(), 'bar3')) {
            echo get_class() . "::bar3()\n";
        }
    }

    public static function bar4() {
        if (method_exists(get_called_class(), 'bar4')) {
            echo get_called_class() . "::bar4()\n";
        }
    }
}

class foo2 extends foo { }

これで、呼び出し側で、

foo::bar1();
foo::bar2();
foo::bar3();
foo::bar4();

と呼ぶと、

foo::bar1()
foo::bar2()
foo::bar3()
foo::bar4()

となり、

foo2::bar1();
foo2::bar2();
foo2::bar3();
foo2::bar4();

と呼ぶと、

foo::bar1()
foo::bar2()
foo::bar3()
foo2::bar4()

となる。

<< 古い記事