Alex Rivera | Logout

Initializing variables outside of PHP constructor

Asked 2012-06-28T16:04:07.250
8

I was looking through the PHP documentation and saw several comments where a variable was initialized outside of a class's constructor, similar to the following:

classMyClass {
    private $count = 0;

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

In PHP Objects, Patterns, and Practice, the author recommends using constructs only for the initialization of properties, deferring any heavy lifting or complex logic to specialized methods. This tutorial (a quick example that 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 would you want to initialize a variable outside the constructor? Is this just sloppy coding, or is there a reason to do something like this? I have to say that until recently, I initialized default values outside the constructor, and there doesn't seem to be any programmatic advantage of one way over the other.

Edit
Report

1 Answer

7

When you initialize a variable outside of the constructor, it must be initialized as a constant. You can't do any operation to initialize it. Thus, the initial value of that member is actually a part of the class signature.

For example, this is invalid:

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

You could do it in the constructor as well, but it would be a bit more verbose and add some clutter to the constructor unless there was some sort of logic going on.

answered 2012-06-28T16:07:56.720

Your Answer