2014-04-01 47 views
-2

是否可以在构造函数中调用函数?是否有可能在构造函数中调用函数? PHP

例如:

class Foo 
{ 
    public $bars = array(); 


    public function __construct($string) 
    { 
     fetchBars($string); 
    } 

    public function fetchBars($string) 
    { 
     $folder = opendir($string); 
     while (false !== ($bar = readdir($folder))) 
     { 
      $this->bars[] = $bar; 
     } 
     closedir($folder); 
    } 
} 

我已经证明行不通的例子。我试图找出是否有可能在构造函数中使用某个函数,但我找不到这个awnser。我知道我可以在构造函数中硬编写这个函数,但是最后我得到了两个代码。如果没有其他选择,我会这样做,但如果有其他选择,请随时分享您的知识!

感谢先进!

亲切的问候

回答

0

是,其可能的,但你需要使用$ this关键字,除非功能是全局的,任何类外。

class Foo 
{ 
    public $bars = array(); 

     public function __construct($string) 
     { 
      $this->fetchBars($string); 
       myfunction(); // this can be called without $this 
     } 

public function fetchBars($string) 
    { 
     $folder = opendir($string); 
     while (false !== ($bar = readdir($folder))) 
     { 
      $this->bars[] = $bar; 
     } 
     closedir($folder); 
     } 
    } 

// this function is outside class. so can be used without $this. 
function myfunction() 
{ 
echo "foo"; 
} 
+0

非常感谢先生! – Khanji

相关问题