【问题标题】:Is it possible to call a function within a constructor? PHP是否可以在构造函数中调用函数? PHP
【发布时间】:2014-04-01 13:29:10
【问题描述】:

可以在构造函数中调用函数吗?

例如:

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);
    }
}

我展示的示例不起作用。我试图找出是否可以在构造函数中使用函数,但我找不到遮阳篷。我知道我可以在构造函数中硬写函数,但最终我得到了双重代码。如果没有其他选择,我会这样做,但如果有其他选择,请随时分享您的知识!

提前致谢!

亲切的问候

【问题讨论】:

    标签: php function constructor call


    【解决方案1】:

    是的,这是可能的,但你需要使用 $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";
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多