Reputation:
I need to write a class where users can set their own values if needed. I need to set default values to the properties.
How would I do this the correct way. Here is an example of what I need to achieve
class Test
{
protected $var1;
protected $var2;
public function __construct($var1, $var2)
{
$this->var1 = $var1;
$this->var2 = $var2;
}
public function setVar1($var1)
{}
public function getVar1()
{}
//etc
}
$var1
should have a default value of true
and $var2
should be a text string, say foo bar
. The user can set new his own values to $var1
and $var2
How would I code these into the example above
Here is my thoughts
defining the values in the constructor like public function __construct($var1 = true, $var2 = 'foo bar')
or setting the values in the declaration of the properties like protected $var1 = true;
Upvotes: 4
Views: 41
Reputation: 434
maybe u need something like this
class Test
{
protected $var1;
protected $var2;
public function __construct($var1=true, $var2='foo bar')
{
$this->var1 = $var1;
$this->var2 = $var2;
}
public function setVar1($var1)
{
$this->var1=$var1;
}
public function getVar1()
{
return $this->var1;
}
}
Upvotes: 2
Reputation: 91744
You can set default values for your method parameters. Note that that also makes them optional when you call your method:
public function __construct($var1 = true, $var2 = 'foo bar')
Upvotes: 3