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 trialYongyu Zhang
1,892 PointsWhat's the difference between our code?
/*****************************
This is my code.
*****************************/
class Fish {
public $common_name;
public $flavor;
public $record_weight;
public function __construct($name,$flavor,$record){
$this -> common_name = $name;
$this -> flavor = $flavor;
$this -> record_weight = $record;
}
}
$bass = new Fish('Largemouth Bass','Excellent','22 pounds 5 ounces');
?>
/********************************
And this is someone else's code.
********************************/
<?php
class Fish {
public $common_name = 'name'; //the difference
public $flavor = 'flavor'; //the difference
public $record_weight = 'weight'; //the difference
public function __construct($name,$flavor,$record){
$this -> common_name = $name;
$this -> flavor = $flavor;
$this -> record_weight = $record;
}
}
$bass = new Fish('Largemouth Bass','Excellent','22 pounds 5 ounces');
?>
Why do they add ='name' after the variable $common_name ?
1 Answer
Shawn Gregory
Courses Plus Student 40,672 PointsHi Yongyu,
When you create properties for classes, like the one's you are talking about, there are two ways you can do it. The first way is the style on the top: you declare the properties then use either a function/method or (if the property is public) an outside script using the class to add values to the properties. The second style is what you see on the bottom. When you declare the property you can also set its value. Both ways are valid PHP syntax and using one over the other is dependable of the situation. If you wish to have default values then you would set a property's value when you declare it, if you don't need a default value or you are sure that you will be setting a value later on, you would just simply declare the property and leave it at that. I'll give you the same link I did in your other post explaining about properties: HERE. Hope this explains things.
Cheers!
Yongyu Zhang
1,892 PointsYongyu Zhang
1,892 PointsThank you so much!