DDMSEO - Full Stack Developer based in London

Optimize your website SEO with X-RAY SEO Auditor

Published: 20th Dec 2017 | Words: 1,301 | Reading Time: 7 minutes

Categories / Tags:

Development
PHP

Using constructors

PHP classes are a way to group related functions and variables. Within classes functions are referred to as methods and variables are referred to as properties. When we initialise a class first we can use what is known as a constructor to run specific functionality as soon as the class is called. The constructor can be looked upon as a function that runs when the class is first called and gives us the opportunity to build values within the class as soon as it’s called.

class testConstruct
{
   public $testVar = 0;

   function __construct()
   {
      $this->initialMethod();
   }

   private function initialMethod()
   {
      $this->testVar = 3;
   }
}

$test = new testConstruct();

echo $test->testVar; // outputs 3

When we initialise our class here we actually call the initialMethod which sets the $testVar property to 3. If we output the $testVar property afterwards it will echo out 3. If we had not run the initialMethod in our constructor the output would be 0, which is the default value we set in our class. This is a fairly simple example but what you can do with constructors is massive. You can run as much logic and functionality initially as you want really. Now you may ask the question why use constructor? You can juts initialise a class and run its methods from outside and modify its properties that way. It’s because you will run into a lot of situations where you absolutely must use a constructor.

Parent Constructors

If you extend parent classes you may wish to use parent properties. These properties may not have the values you want originally but you can call the parent constructor to build exactly what you need for the child class. A parent constructor does not run unless you call it in the child class. The benefit of this is you may wish to use values within the parent that you don’t want modified by the constructor functionality.

class parentClass
{
   protected $testVar = 0;

   function _construct()
   {
      $this->changeValue();
   }

   function changeValue()
   {
      $this->testVar = 3;
   }
}

class childClass extends parentClass
{
   function __construct()
   {
      parent::__construct(); // now if we call $testVar in our child class it has the value of 3 
   }
}

In the simple example above we see that we can use the parent constructor to run specific values for the child class. While the example above is extremely crude it’s the simple logic behind it is what you should follow. If you have multiple classes extending a parent class you can push a lot of functionality to the parent if the functionality is the same across child classes. Instead of having the same functions across a few different child classes you can move them to the parent and use the constructor to run them if need be. The constructor gives you control over the parent class and you can have a chain of multiple child classes each calling the constructor of the one above.

Dependency injection

In large and complex applications it can take dozens of classes just to get a web page to run. You can have every class fulfil a very specific role and in turn you put yourself into the position where many classes will be dependent on values from other areas of your application to run. Dependency injection is where you inject specific values into a class which are required by it to function as intended. The constructor is the perfect place to do this, right where the class first runs. A typical example is if a class requires database functionality. You can inject a database object into the constructor.

class testInjection
{
   function __construct($db)
   {
      $this->db = $db;
   }
}

$test = new testInjection($db);

In the example above a database object is passed in and assigned to a property within the class. If for some reason the class is initialised without a value an error will be thrown.

$test = new testInjection(); // would create an error

Some classes you create may or may not need a value inject into the constructor. In this case we can make the value optional by simply setting a default value.

function __construct($db = "") // Now we can initialise this class with or without an injected value.

$test = new testInjection($db); // works  

$test = new testInjection(); // also works

Type hinting

The often will be times where you will inject a class into another class. Class instances can hold multiple properties and methods which can be used within the injected class. Because of this fact you may need a specific class and only that class to be injected. Type hinting provides a way to ensure the right class is injected or an error will be throw.

function __construct(databaseClass $db)

We declare the name of the required class just before our injected variable. This is a very simple example. If you use things like namespaces things get a bit more complicated but as a simple example this shows you how to ensure you have the right class injected. Whenever you need something specific within a class constructor you should always type hint it. This creates a robust structure to your application ensuring the right things are required in the right places and also provides a hint to other developers working on projects about what is needed.

Rate this article

Average: 0.00 out of 5 / Votes: 0

Comments

Please login or register to post comments

Login | Register