Initialization of variables outside the PHP constructor

I was looking at the PHP documentation and saw some comments where the variable was initialized outside the class constructor, similar to the following:

classMyClass {
    private $count = 0;

    public function __construct() {
        //Do stuff
    }
}

In PHP objects, templates, and practice, the author recommends using constructs only to initialize properties, putting aside any heavy or complex logic to specialized methods. This tutorial (a quick example I found on Google) also recommends using constructors to initialize properties: http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-3.php .

Why do you want to initialize a variable outside the constructor? Is it just sloppy coding, or is there a reason to do something like this? I have to say that until recently, I initialized the default values ​​outside the constructor, and there seems to be no software advantage in one way over the other.

+5
source share
3 answers

When you initialize a variable outside the constructor, it must be initialized as a constant. You cannot perform any operation to initialize it. Thus, the initial value of this element is actually part of the class signature.

For example, this is not true:

private $var = $othervar;
private $var = func();

, , - .

+5

, , , , :

,

? , - , .


:

PHP , . , undefined, NULL ():

class A {}

$a = new A;

var_dump($a->property); # NULL

(), PHP . - NULL , (Demo):

class A {
    public $property;
}

$a = new A;

var_dump($a->property); # NULL

. , - ( , ). ():

class A {
    public $property = 'hello';
}

$a = new A;

var_dump($a->property); # string(5) "hello"

, , . , , .

+2

... . Java/++, , - .

0

All Articles