我的类看起来像这样:
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,填写什么标记"????"有人可以帮助我?
if(method_exists(__CLASS__, $method))
在一个简单的单类情况下,您可以使用 __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次,你吠错了树。