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) Properties and Methods Constructor Method

Kim Gee
Kim Gee
3,841 Points

getInfo()

Shouldn’t the getInfo() have arguments? Why not? Do you see anything wrong with this code?

<?php 
class Product
{
    public $name = 'default_name';
    public $price = 0;
    public $desc = 'default_ description';

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

   public function getInfo(){
        return "Product Name: ". $this->name. " Price: ". $this->price. " Description: ". $this->desc;
    }
$shirt = new Product("Space Juice T-Shirt", 20, "Awesomre Grey T-Shirt");
$soda = new Product("Space Juice Soda", 2, "Grape Flavored Mutilator");

echo $shirt->getInfo();

2 Answers

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Kim,

There's no need to pass arguments to getInfo(). The purpose of the method is to describe the instance its being called on. This can be accomplished without passing any arguments to it, since it can access the properties name, price and description using the keyword $this.

Also, your constructor method isn't quite right. Right now you're setting the property name three times, and not setting the price or desc properties at all. Instead, you want to set each property using the arguments that are passed in when creating the Product instance, like this:

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

Let me know if this helps!

Kim Gee
Kim Gee
3,841 Points

Thank you Greg.

Greg Kaleka
Greg Kaleka
39,021 Points

No problem!

Happy Coding!