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

Constructor Method - Code not showing output as shown by Hampton

<?php 

// Class Definition
class Product
{
    //properties
    public $name = 'default_name';
    public $price = 0;
    public $desc = 'default_ description';

    //Presetting properties to be initiated uppon creation of an object
    function __construct($name, $price, $desc){
        $this->name = $name;
        $this->name = $price;
        $this->name = $desc;
    }

    //methods
    public function getInfo(){
        return "Product Name: ". $this->name;
    }
$p = new Product();
$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();
?>

3 Answers

Hey Kudakwashe,

You need to use each of those public properties you created inside of the construct. It looks like you are only using the name property.

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

Thanks Marcus

You're welcome, Kuakwashe! Happy Coding!

That's weird. When I use Workspaces, using only the name property is fine yet when I try to run the same code through a Web server I get errors since I didn't use the other two properties. Once I modified the return statement in the getInfo method to return info about the other two properties, it works. Why does Hampton's code work in Workspaces but not through the local Apache web server on my machine? I'm using WAMP that is bundled with Apache 2.4.9 and PHP 5.5.12. Could it be the version of PHP that I am using?