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 trialTim Cosson
17,006 Pointshow do i use the __constructor?
im on the 1st task.
<?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
4,213 PointsSo 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();
?>