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 Object Inheritance

Code not returning string

I'm doing the Object Inheritance track and i've copied, from what i can see, the code written by the tutor exactly as they have it, however for some odd reason the $flavor i.e. Grape isn't returned, but the rest of the object is. Any ideas?

class Product {

    public $name = 'default_name';
    public $price = 0;
    public $desc = "default description";

    function __construct($name, $price, $desc) {
        $this->name = $name;
        $this->price = $price;
        $this->desc = $desc;
    }

    public function getInfo() {
        return "Product Name: " . $this->name;
    }
}

class Soda extends Product {

    public $flavor;

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

    public function getInfo() {
        return "Product Name: " . $this->name . " Flavor: " . $this->flavor;
    }
}

$shirt = new Product("Space Juice T-Shirt", 20, "Awesome Grey T-Shirt");
$soda = new Soda("Space Juice Soda", 2, "Thirst mutilator", "Grape");

echo $soda->getInfo();```

2 Answers

Mike Costa
PLUS
Mike Costa
Courses Plus Student 26,362 Points

When you extend the class Product to Soda, you're calling the parent __construct() method, which will initialize its parents values that you are passing into the child object. The Soda construct method has 4 parameters, $name, $price, $desc, and $flavor. The parent constructor is taking care of the first 3, but you're not doing anything with the last one, $flavor. So its not going to get returned.

public $flavor;
 function __construct($name, $price, $desc, $flavor) {
        parent::__construct($name, $price, $desc);
        $this->flavor = $flavor;
    }

It's amazing how such simple thing pass you by when you're attempting to continue learning PHP at 1am. Thanks Mike.