Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a reason to set a value for variables in the constructor of a class rather than when you declare them? I realize you can't pass data into the variables if you try to set them when they are declared, but what about things that will always be the same ( i suppse 'always' is a tough claim to make )?

class variables_set_outside_constructor
{
     private $admin_name = 'jeff';
     private $current_working_directory = get_cwd();

     function __construct() {}
}

as opposed to this:

class variables_set_inside_constructor
{
     private $admin_name;
     private $current_working_directory;

    function __construct()
    {
         $this->admin_name = 'jeff';
         $this->current_working_directory = get_cwd();
    }
}

What are the advantages and disadvantages of settings values in the constructor versus when they are declared? I'm curious about any language agnostic aspects as well.

like image 487
T. Brian Jones Avatar asked Sep 16 '11 11:09

T. Brian Jones


1 Answers

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.

like image 172
hakre Avatar answered Sep 22 '22 16:09

hakre