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

Yan Liu
Yan Liu
10,552 Points

Help for Constructor Method

Hi guys, just watching this constructor video. However, my code is not working. Please spot out. Thanks.

<?php 
class Product 
{
    //property
    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;    

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

    //class definations go here!    
}

$p = new Product();
$shirt = new Product("Space 1", 20, "cool");
$soda = new Product("space 2", 233, "hot");

echo $shirt->getInfo();

?>

1 Answer

Jayden Spring
Jayden Spring
8,625 Points

Change your construct to have default values of '' for each variable; function __construct($name='', $price = 0, $desc='') { if($name != '' && $price > 0 && $desc != '') { ...Code... } }

The problem with your script is you are calling the constructor without any arguments when you create an instance of the class and assign it to $p - PHP would throw an error.