Skip to content

Latest commit

 

History

History
100 lines (67 loc) · 2.42 KB

3.md

File metadata and controls

100 lines (67 loc) · 2.42 KB

Lesson 3: Constructors and Type Hinting

New Keywords:

  • __construct

Constructors

In the previous exercise, we created a class and instantiated it. We then manually set the properties of the object.

It is often helpful to be able to be able to create an instance and initialize it at the same time.

Fortunately, we can do this with a special constructor method. In PHP the constructor method is named __construct. Any method you see in object oriented PHP with two leading underscores is a magic method provided by the language.

Consider the following:

<?php

class Person {

  private $name;

  public function __construct($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }

}

In the above example the $name value is required each time we instantiate a class. The following example will return an error.

<?php

$myperson = new Person();

You can allow an object to be instantiated with default values by setting the constructor to use default values on the arguments, like for any other PHP function.

<?php

class Person {
  private $name;

  public function __construct($name = NULL) {
    $this->name = $name;
  }
}

Typing Data

We can use type hinting to ensure that arguments passed to methods (or any PHP function in general) are of a certain type.

<?php

class Person {
  private $name;
  private $mom;

  public function __construct($name = NULL) {
    $this->name = $name;
  }

  public function setMom(Person $mom) {
    $this->mom = $mom;
  }
}

If the given value is of the incorrect type, then an error is generated:

  • In PHP 5, this will be a fatal error.
  • PHP 7 will throw a TypeError exception.
<?php

$person = new Person('Bart');
$mom = new Person('Marge');

$person->setMom('Marge'); // Will generate exception.
$person->setMom($mom); // Works.

Exercise:

  1. Using the class from Lesson 2, create a constructor function that takes a $name parameter and assigns that value to the name property.
  2. Add the 'mom' property, and getters and setters.
  3. Make use of type hints in the arguments to the methods.
  4. Try instantiating the person with and without arguments to see what happens.
  5. Try calling the "setMom()" method with different versions of the arguments to see what works and what gives errors. Try to write code that handles errors in an elegant way.