开发者

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

开发者 https://www.devze.com 2023-04-05 03:22 出处:网络
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 de

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_i开发者_C百科nside_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.


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.


For ease of access. Declaring them all in one central location allows you to, well see a list of all variables.

It's not a big deal if you declare them when it is created if you are on a solo project. If you are working with teams it makes more sense to follow some standard so you don't get confused.


Although not flexible, setting variables when you declare it may be useful if you plan to use a class without creating an instance for some reason:

class MyClass {
  public $MyVar = 'hello';

  function MyFunction() {
    return self::MyVar;
  }
}

echo MyClass::MyFunction();


it can help to fetch record from database once and reuse records. like i have done with tankauth login library.

class Welcome extends CI_Controller{
    public $id;
    function __construct(){
        parent::__construct();
        $this->id = $this->tank_auth->get_user_id();
    }
function index(){ $this->MyModel->get_user($this->id);}
function admin(){ $this->MyModel->get_admin($this->id);}
function profile(){ $this->MyModel->get_profile($this->id);}
}


Personally I like to declared variables inside constructor due its easier to managed them. If I have a class with tons and tons of methods, then it would be a pain in the a** to find where the variable is declared or even worse, let say we are getting a POST request, what could happen if I forget to sanitize and validate this post. SQL injection... If you've all your server request within the constructor you can easily find them all, let say create a method that sanitize depending on what you're expecting and then you'll be secured against those attacks.

example:

 <?php  
     Class Example extends Core_Controllers 
     {
         private $_var = null;

         public function __construct(){

              if( isset($_POST['number']) ):
                $this->_var = $this->santizeNumber($_POST['number']);
              else:
                 $this->_var = "Not Declared Yet";
              endif;

             $this->methodToCall();
         }
      }


       public function sanitizeNumber($number){
              return filter_var($number, FILTER_SANITIZE_NUM_INT );
       }

       public function methodToCall(){
           echo $this->_var;
       }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号