Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Object-Oriented PHP Basics Building the Recipe Controlling the Class

how do i use the __constructor?

im on the 1st task.

fish.php
<?php

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

    public function getInfo() {
      return "A {$this->common_name} is an {$this->flavor} flavored fish. The world record weight is {$this->record_weight}.";
    }
}

?>

1 Answer

Shayne Laufenberg
Shayne Laufenberg
4,213 Points

So I've posted below an example of how to use a construct function in php in the current Challenge be aware that inside a construct its always best to validate the information being sent. In this example I've used a basic strval check on our variables since the data that should be stored should be a string. This is so that our class doesn't get confused if a developer passes the object another datatype. There are other more advanced ways to validate our parameters inside our construct function but for this example its not really needed, since its just getting you used to object oriented programming. I've posted a solution to the problem so you can compare your code and understand how to properly write a constructor function, hope it helps :)

Solution:

<?php

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

    public function __construct($name, $flavor, $record){

      // Set Common Name to our Given Name //
      $this->common_name = strval($name);

      // Set Flavor to our Given Flavor //
      $this->flavor = strval($flavor);

      // Set Record Weight to our given Record Weight //
      $this->record_weight = strval($record);

    }

    public function getInfo() {
      return "A {$this->common_name} is an {$this->flavor} flavored fish. The world record weight is {$this->record_weight}.";
    }
}

// Create new Fish Object //
$bass = new Fish("Largemouth Bass", "Excellent", "22 pounds 5 ounces");

// Display Fish Information //
echo $bass->getInfo();

?>