Why set variables inside the construct of a PHP class when you can set them when they are declared? Why set variables inside the construct of a PHP class when you can set them when they are declared? php php

Why set variables inside the construct of a PHP class when you can set them when they are declared?


You have an error in your question. This does not work in a class:

class foo{   var $mysqli = new mysqli( 'host', 'name', 'pass', 'directory' );}

Try the Demo to see what does not work here.

So maybe one (!) reason to write

class foo{   var $mysqli;   public function __construct()   {       $this->mysqli = new mysqli( 'host', 'name', 'pass', 'directory' );   }}

is because there is no alternative to it (between the two alternatives you offered in your question only, naturally. This is horrorful bad practice to do so w/o a delicate design based on dependency injection and other high-level design abstractions - or more precise: This is making mysqli a dependency of foo - including the database configuration).

Next to that, please don't use var, use private, protected or public instead.


First reason: re-usability.

Second reason: The credentials for your database connection don't belong in a database class, this should be handled in your application. Your class should only know how to accept and use them - not define them.

A good example case is having other login information on your development machine then on your staging/live machine. This instantly shows you the problem with declaring in the constructor.


I didn't notice what the attempt was until your comment. I'm not used to see var anymore I guess. Luckily I wasn't the only one. Of course declaring like that is impossible.


You might find this article on Java object initializers to be of some interest.

Although many of the concepts in the article are specific to Java and not relevant to PHP, you might find some of these points interesting:

  • Before you use a property in a class, you generally want it to be initialized to some value (in PHP, this is not a requirement, but in practice I rarely see this guideline violated). If you have multiple constructors then you have to initialize the property in each constructor meaning there will be a lot of copying and pasting. (PHP also has multiple contructors:)

  • In Java subclasses, only the "no-arg" parent constructor is called by default, which means that you can't guarantee that a subclass will call the "correct" constructor. In PHP, the problem is compounded because you can't guarantee that the subclass will call the parent class' constructor at all. Initializing properties directly in the parent class declaration ensures that those properties always start off initialized, even if the subclass constructor doesn't initialize them.