检查调用静态方法php

时间:2014-04-01 14:52:29

标签: php

我的课程看起来像这样:

class Foo
{
    puclic static function blindPaths($paths)
    {
        foreach($paths as $name=>$path)
        {
             $method='set'.ucfirst($name).'Path';
             if(method_exists(????,$method))
                 self::$method($path);
        }
    }

    public function setBasePath($base)
    {
       //do something...
    }

    public function setAppPath($app)
    {
       //do something...
    }

    ....
}

现在,我打电话给:

$paths = array(
    'base'=>'path.of.base.path',
    'app'=>'path.of.app.path',
    'someValue'=>'path.of.someValuePath',
    ....
);
Foo::blindPaths($paths);

检查method_exists时出现问题,填写那些标记的内容“????”有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:2)

if(method_exists(__CLASS__, $method))

答案 1 :(得分:1)

在简单的单类情况下,您可以使用__CLASS__常量作为method_exists调用的第一个参数,但是如果您处于在父类中定义静态方法的情况等级(或抽象类,或其他地方),那么也许你可能想要考虑这个:

puclic static function blindPaths($paths)
{
    $current = get_called_class();
    foreach($paths as $name=>$path)
    {
        $method='set'.ucfirst($name).'Path';
        if(method_exists($current,$method))
            self::$method($path);
    }
}

或者,如果你将界面和Trait添加到混合中:

puclic static function blindPaths($paths)
{
    $current = get_called_class();
    $current = new $current;//create instance
    foreach($paths as $name=>$path)
    {
        $method='set'.ucfirst($name).'Path';
        if($current instanceof Foo)
            self::$method($path);
        elseif ($current instanceof Bar)
            return $this->{$method}($path);
    }
}

但无论如何,重新考虑你的设计。如果你使用的结构类似于现在的结构,那么10次中有9次,你正在咆哮错误的树。

相关问题