Setting default values โ€‹โ€‹for properties in a class

I need to write a class in which users can set their own values, if necessary. I need to set default values โ€‹โ€‹for properties.

How I would do it right. 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
}

$var1should have a default value trueand $var2should be a text string, for example foo bar. User can set new own values $var1and$var2

How would I encode them in the example above

Here are my thoughts

  • defining values โ€‹โ€‹in the type constructor public function __construct($var1 = true, $var2 = 'foo bar')

  • or setting values โ€‹โ€‹in a property declaration, such as protected $var1 = true;

+4
source share
2 answers

. , :

public function __construct($var1 = true, $var2 = 'foo bar')
+3

, -

  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;
  }


}
+2

All Articles