我知道您可以在 PHP 中使用嵌套函数。
这是问题:
我有这个代码:
class ClassName
{
private $data;
function __construct()
{
}
public function myFunction()
{
if($condition1 != NULL)
{
if(!empty($condition2) && $this->data->condition3 == NULL)
{
$this->do1($condition2);
$this->do3($condition2);
$this->do3($condition2);
$this->doBLAH();
}
elseif(empty($checkoutItem->rebillCheckoutItemId))
{
$this->do1($condition2);
$this->do3($condition2);
$this->do3($condition2);
$this->doSomethingElse();
}
}
}
}
如您所见,这部分是多余的:
$this->do1($condition2);
$this->do3($condition2);
$this->do3($condition2);
所以摆脱冗余,我可以创建一个新方法:
private function doSomething($condition2)
{
$this->do1($condition2);
$this->do3($condition2);
$this->do3($condition2);
}
但我不想。它可能真的把我的代码搞砸了。
只是想知道是否可以做类似的事情:
public function myFunction()
{
if($condition1 != NULL)
{
if(!empty($condition2) && $this->data->condition3 == NULL)
{
$this->doSomething($condition2);
$this->doBLAH();
}
elseif(empty($checkoutItem->rebillCheckoutItemId))
{
$this->doSomething($condition2);
$this->doSomethingElse();
}
}
function doSomething($condition2)
{
$this->do1($condition2);
$this->do3($condition2);
$this->do3($condition2);
}
}
我试过了,但它抛出了一个Fatal error: Call to undefined function doSomething()
. 有什么技巧吗?难道我做错了什么?
更新
我在 YII 框架中工作,它给了我一个例外:BlahWidget and its behaviors do not have a method or closure named "doSomething"