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 trialPrath M
9,631 PointsWhy do we need the Construct method at all if we have to use the class names in the getInfo() function?
What was the point of re-naming the internal properties in the constructor method? The getInfo() function still relies on the class' public name so I guess I don't understand what the point of this was: $this->common_name = $name;
<?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;
}
public function getInfo() {
return "A " . $this->common_name . " is an " . $this->flavor . " flavored fish. " . "The world record weight is " . $this->record_weight . ".";
}
}
$bass = new Fish("Largemouth Bass","Excellent","22 pounds 5 ounces");
?>
1 Answer
Shawn Gregory
Courses Plus Student 40,672 PointsPratham,
The constructor is actually being used. It is used every time you instantiate the class. You are using the constructor to input the values you are going to use later on using the getInfo() function. Constructors are there to perform actions whenever the class gets instantiated while a destructor is used when the class is destroyed (or when the script finishes). Remember from the video and the challenges that you are adding information when you first use the class. The constructor is being called and storing the information you provided it into the member variables.
As for the reason why you would use the constructor to store the information, there will be times when you will want the members to be private or protected and therefor you would be unable to add values from outside the class. You would use methods to add the values to the class. Finally, this way is simply cleaner code that you do not have to type. Plus since this is a simple class in a simple example, this method would be recommended. I hope this clears things up.
Cheers!