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 trialcarlosjimenez
5,504 PointsWhy do we have default values for class properties?
If we do not pass in arguments in our echo statement, we get an error instead of seeing the default values displayed. So i'm confused. I get why we are declaring the properties, but do not understand why we are giving them default values.
class Product {
public $name = 'default name';
public $price = 0;
public $desc = 'default description';
function __construct($name, $price, $desc) {
$this->name = $name;
$this->price = $price;
$this->desc = $desc;
}
public function getInfo() {
return "Product Name: ". $this->name;
}
}
$testObj = new Product("James Brown", 1000, "The most amazing man");
echo $testObj->getInfo();
2 Answers
Adam Young
15,791 PointsDepending on your application, there's no need for a default value. I think a potential reason for giving a default value would be to use the default value as part of a conditional check:
<?php
class Example {
public static $name = "doug";
function __construct($name=null) {
//Checks value of $name, if it doesn't equal the default value
//then set the argument passed into Example() as $name
if ($name != "doug")
{
$this->name = $name;
}
else
{
$this->name = self::$name;
}
}
public function get() {
if (is_null($this->name)) {
return "No name given";
}
return $this->name;
}
}
$test = new Example("frank");
echo $test->get();
?>
shezazr
8,275 PointsSometimes it is good to give a default value so that when coding you don't have to explicitly set that default value when creating that object & consequently saving it to the db.. saves you some lines..
Here is an example.. usually on websites they may have a user status (which could be live|banned|need_activation.. and you would set this to last one in this case as newly registered user would need to activate their account by clicking on a link in the email..
Another one would be user type.. again a newly registered user would most likely be a user and not admin or a mod.. so you could set that to default value of user..
In the end you don't have to have a default value (Like mentioned above) if it doesnt make sense for your application.