2011-10-19 47 views
2

我可以在CodeIgniter中编写可链接函数吗?Codeigniter可编写链接函数

所以,如果我有这样的功能:

function generate_error(){ 
    return $data['result']  = array('code'=> '0', 
             'message'=> 'error brother'); 
} 

function display_error(){ 
     $a= '<pre>'; 
     $a.= print_r($data); 
     $a.= '</pre>'; 
     return $a; 
} 

我想通过链接他们叫那些:

echo $this->generate_error()->display_error(); 

我为什么要单独的这些功能的原因是因为display_error()是只对开发有用,所以当涉及到生产时,我可以删除display_error()或类似的东西。

谢谢!

回答

2

要编写可链式函数,他们是一个类的一部分,然后从该函数返回对当前类的引用(通常为$this)。 如果你返回除了对类的引用以外的任何东西,它将会失败。

它也可能返回引用到其他类(例如,当您使用的代码点火器活动记录类get()函数返回给DBresult类的引用)

class example { 

    private $first = 0; 
    private $second = 0; 

    public function first($first = null){ 
    $this->first = $first; 
    return $this; 
    } 

    public function second($second = null){ 
    $this->second = $second; 
    return $this; 
    } 

    public function add(){ 
    return $this->first + $this->second; 
    } 
} 

$example = new example(); 

//echo's 15 
echo $example->first(5)->second(10)->add(); 

//will FAIL 
echo $example->first(5)->add()->second(10); 
0

你应该返回$this您函数在php中做连锁函数

 

public function example() 
{ 
// your function content 
return $this; 
}