Storing default type value in class member declarations

63 views Asked by At

In PHP (and other dynamically typed languages), is storing type relative default values in class member declarations bad practice? Does it affect performance in any way?

PHP example of what I mean:

class Example {
  protected $someNumber = 0;
  protected $someThings = [];
  protected $someString = "";
}

versus setting defaults in constructor or not setting anything at all until the member is actually used.

class Example {
  // members are NULL by default
  protected $someNumber;
  protected $someThings;
  protected $someString;

  __construct() {
    $this->someNumber = 0;
    $this->someThings = [];
    $this->someString = '';
  }
}

I have habit of assigning default type values in declaration, when it comes to variables used for storing values other than objects. In a dynamically typed language like PHP this gives me an instant overview when inspecting a class, as we can't typehint member declarations. Otherwise I feel like I would have to resort to Hungarian notation in order to have some sense in my code.

1

There are 1 answers

0
deceze On BEST ANSWER

There's nothing wrong with declaring default values for properties whatsoever, on the contrary, I'd see it as very good practice. That's what the syntax is for. Performance-wise it should, if anything, be faster, since the values are only statically allocated once during parsing.