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

时间:2014-04-01 13:29:11

标签: php function constructor call

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

例如:

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。我知道我可以在构造函数中硬编写函数,但最后我得到了双重代码。如果没有其他选择,我会这样做,但如果还有其他选择,请随时分享您的知识!

先谢谢!

亲切的问候

1 个答案:

答案 0 :(得分: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";
}
相关问题