Search code examples
phpfunctionconstructorcall

Is it possible to call a function within a constructor? PHP


Is it possible to call a function within a constructor?

For example:

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

The example i've shown does not work. I've tried to find out if it is possible to even use a function within a constructor but I couldn't find the awnser. I know that I can just hard-write the function within the constructor, but then I end up with double code. If there is no other option, I will do so, but if there is an other option feel free to share your knowledge!

Thanks in advanced!

Kind regards


Solution

  • Yes ,its possible but you need to use $this keyword unless function is global and outside any class.

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