Search code examples
phplaravelclass-constructors

Laravel command cannot call $this->info() in child class


I'm just starting out with the basic concepts OO in PHP,

Foo.php

class Foo extends Command {


    public function __construct()
    {
        parent::__construct();
    }

    public function fire()
    {
        $bar = new Bar();
    }

}

Bar.php

class Bar extends Foo {

    public function __construct()
    {
        parent::__construct();
        $this->info('Bar');

    }
}

When I run Foo::fire() it gives: Call to undefined method Foo::__construct(). But Foo clearly has a constructor, what am I doing wrong?

Another thing I suspect is that it might be a Laravel problem rather than PHP. This is an artisan command that I created.

EDIT:

Also calling $this->info('Bar') anywhere in Bar will also give Call to a member function writeln() on a non-object. Why can't I call a parent's method from the child class?


Solution

  • I also ran into this issue, and felt Marcin's feedback to be cold and unhelpful, especially in his comments. For that I am happy to respond with this answer to you and anyone else who stumbles on this problem.

    In the original class Bar:

    class Bar extends Foo {
    
         public function __construct()
         {
            parent::__construct();
            $this->info('Bar');
        }
    }
    

    I just needed to set the property of 'output' like the following:

    class Bar extends Foo {
    
         public function __construct()
         {
            parent::__construct();
            $this->output = new Symfony\Component\Console\Output\ConsoleOutput();
            $this->info('Bar');
        }
    }
    

    Hope this is helpful!