1

I just wonder what is the best way to assign default value in PHP Class.

Example: The PHP constructor __construct() method is the first method will be read whenver the class is called. So here's some code:

class A{
   private $x;

   public function __construct(){
       //Var x iniated in constructor method
       $this->x = "some values";
   }
}

Example above I put x variable to "some values" in constructor method.

And I tried this (below codes) too and it works the same.

class A{
    private $x = "some values";

    public function __construct(){
        //Var x initiated out of constructor method
    }
}

My question is, which one is the best practice?

2
  • 2
    If the value is a literal (string, numerical value, array), put it in the variable declaration. If it is an expression (function call, calculation), put it in the constructor. Commented Dec 29, 2017 at 7:38
  • If $x is always the same, you should do it as in the second case you posted. If the value should be browsable like $here->x then make it public. Otherwise make it private. Commented Dec 29, 2017 at 7:43

1 Answer 1

3

TL;DR; Use default values as much as possible for readability, when you can't assign value as default, use function to set it.


If you are using static method, then no __construct will be called, so your value will be not set.

If it's literal value, it's best to set it as default value (private $x = 'some value'), otherwise use constructor/setter/factory methods for this value to be set:

private static $x;

public function getX() {
    if (empty(self::$x)) {
        self::$x = new XClass();
    }

    return self::$x;
}

public function randomTest() {
    $x = $this->getX()->callMethod()->doStuff();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.