Best way to initialize a class variable

I searched for a while, but I could not find the answer, what are the differences between these two ways to inicialize a variable class in PHP? :( if there is)

class MyClass { private $myVariable='something'; public function __construct() { } } class MyClass { private $myVariable; public function __construct() { $this->myVariable='something'; } } 
+4
source share
4 answers

See this scenario :

 class Parent { protected $property1; // Not set protected $property2 = '2'; // Set to 2 public function __construct(){ $this->property1 = '1'; // Set to 1 } } // class Parent; class Child extends Parent { public function __construct(){ // Child CHOOSES to call parent constructor parent::__construct(); // optional call (what if skipped) // but if he does not, ->property1 remains unset! } } // class Child; 

This is the difference between the two challenges. parent :: __ construct () is optional for child classes that inherit from the parent. So:

  • if you have a scalar (as in is_scalar() ) properties that need to be pre-configured, do this in the class definition that they exist in child classes as well.
  • If you are properties that depend on arguments or are optional , put them in the constructor .

It all depends on how you create your code functionality.

There is no right, this is just what suits you.

+2
source
  • If you want to initialize the variable with the default value inside the class, select method 1.
  • If you want to initialize the variable with an external value, pass the variable through the constructor and select method 2.
+3
source

You can only use constant values ​​if you do not want to initialize the variable in the constructor. Here is a small example:

 define('MY_CONSTANT', 'value'); class MyClass { // these will work private $myVariable = 'constant value'; private $constant = MY_CONSTANT; private $array = Array('value1', 'value2'); // the following won't work private $myOtherVariable = new stdClass(); private $number = 1 + 2; private $static_method = self::someStaticMethod(); public function __construct($param1 = '') { $this->myVariable = $param1; // in here you're not limited $this->myOtherVariable = new stdClass(); $this->number = 1 + 2; $this->static_method = self::someStaticMethod(); } } 

Take a look at this manual page to see which values ​​allow you to directly evaluate properties: http://php.net/manual/en/language.oop5.properties.php

There may be more differences ...

+1
source

I like to do this as a second way to facilitate lazy loading. Simple values ​​that I will specify when declaring a member variable.

 class WidgetCategory { /** @var array */ private $items; /** * * @return array */ public function getItems() { if (is_null($this->items)) { $this->items = array(); /* build item array */ } return $this->items; } } 
+1
source

Source: https://habr.com/ru/post/1443073/


All Articles