5

Doing a var_dump on an object from either of the two classes gives the same result

Class Node{
    public $parent = null;
    public $right = null;
    public $left = null;        
    function __construct($data){
        $this->data = $data;                    
    }
}

Class Node{
    public $parent;
    public $right;
    public $left;        
    function __construct($data){
        $this->data = $data;                    
    }
}

For example

$a = new Node(2);
var_dump($a);

returns the following for either of the above classes

object(Node)#1 (4) {
  ["parent"]=>
  NULL
  ["right"]=>
  NULL
  ["left"]=>
  NULL
  ["data"]=>
  int(2)
}

This doesn't seem to be the case for variables.

$b;
var_dump($b);

If you intend for the property to have a value of null is there a need to explicitly write that since php seems to do it automatically for you?

Also - According to this answer https://stackoverflow.com/a/6033090/784637, C++ gives undefined behavior if you try to get the value of an uninitialized variable. Does C++ automatically set the value of a property in a class to null the way php does, if that property is uninitialized to a value?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user784637
  • 15,392
  • 32
  • 93
  • 156

3 Answers3

3

No, there is no need to initialize them to null -- PHP does this automatically and doing it yourself does not produce any observable difference.

C++ does not set values of class fields to null (there is actually no "real" null value in C++ unless you count nullptr in C++ 11); it zero-initializes or value-initializes them, which is not the same. You can read about zero- and value-initialization here.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
2

Save yourself the keystrokes; There's no need to set properties' initial values to null. In PHP internals AFAIK, properties are already assigned null if you don't explicitly set them; your var_dump proves that. Class properties are not considered the same as raw variables in PHP, thus the difference in your var_dump results.

However, doing so doesn't seem to harm anything. I used to set them as null in my Doctrine entity classes, and it made no difference in any phase of the entity's lifetime.

1

Nope, in PHP there's no such thing as undefined, so it's the same if you don't initialize with null. Some people are used to it from other programming languages, or write that just to make sure, but there's no difference.

C++ is very different, but I don't have enough knowledge to give you an answer about that.

Eduard Luca
  • 6,514
  • 16
  • 85
  • 137