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 Mid-Course Challenge

Andrew Walters
Andrew Walters
8,876 Points

PHP Constructor Code Challenge

In the new constructor method, assign each of the properties on the Fish class with its corresponding parameter variable. I've looked at this every way I can and I just cannot understand it. Can anyone help me with the answer and explain why please? Thanks! Here's my code so far:

<?php

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

    function __construct($name, $flavor, $record){
    $this->name = $name;
    $this->flavor = $flavor;
    $this->record = $record;
    }
}
?>
fish.php
<?php

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

    function __construct($name, $flavor, $record){
    $common_name->name = $common_name;
    $this->flavor = $flavor;
    $this->record = $record;
    }
}
?>
Andrew Walters
Andrew Walters
8,876 Points

Oops. didn't mean to post that twice, sorry!

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey Andrew.

What you need to do is use the $this to assign the specific instances of the variables in the construct to the variables already declared the class.

<?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;
    }
}
?>

Hampton explains more clearly than I can in this video starting at about the 1:05 mark.

Hope this helps! Keep Coding! :)

Andrew Walters
Andrew Walters
8,876 Points

Weird, I tried that code earlier and I got it wrong, just tried it again and I got it right. Strange. Thanks so much for the help!

There was probably a small typo somewhere in the code you first tried.