Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Object-Oriented PHP Basics (Retired) Inheritance, Interfaces, and Exceptions Final Challenge

Kenn Hyatt
Kenn Hyatt
9,683 Points

Why not use the parent keyword?

In the video about object inheritance, the teacher used the "parent" keyword when creating the constructor class, kinda like this:

<?php

 function __construct($name, $flavor, $record) {
    parent::__construct($name, $flavor, $record);
  }

but when I do it its wrong.

I had to do this:

<?php

 function __construct($name, $flavor, $record) {
    Fish::__construct($name, $flavor, $record);
  }

Why cant I use the "parent" keyword here?

fish.php
<?php

class Fish
{
    public $common_name;
    public $flavor;
    public $record_weight;

    function __construct($name, $flavor, $record){
        $this->common_name = $name;
        $this->flavor = $flavor;
        $this->record_weight = $record;
    }

    public function getInfo() {
        $output  = "The {$this->common_name} is an awesome fish. ";
        $output .= "It is very {$this->flavor} when eaten. ";
        $output .= "Currently the world record {$this->common_name} weighed {$this->record_weight}.";
        return $output;
    }
}

class Trout extends Fish {

}

2 Answers

To call parent, you have to make sure the object you're inside extends another object - i.e. it has a parent. So the first thing I would check is if I'm calling parent in the right place.

<?php

class SomeParent
{
    function __construct()
    {
        // This won't work, because it doesn't extend another class (and has no parent)
        parent::__construct();
    }
}

class SomeChild extends SomeParent
{
    function __construct()
    {
        // This will work because it does extend a class (and has a parent)
        parent::__construct();
    }
}

In your example, you'll only be able to call parent methods in the Trout class, which extends fish.

Is this what you're doing already?

Kenn Hyatt
Kenn Hyatt
9,683 Points

Yes that makes so much more sense

Thank you