Skip to content

Latest commit

 

History

History
74 lines (51 loc) · 1.96 KB

3.md

File metadata and controls

74 lines (51 loc) · 1.96 KB

#Lesson 3: Constructors and Type Introspection

##New Keywords:

  • __construct
  • is_a()

##Constructors

In the previous exercise, we created a class and instantiated an object based on the class. We then manually set the values of properties of the object.

It is often helpful to be able to be able to declare an instance and assign values 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 special method provided by the language.

Consider the following:

<?php

class Person {
  private $name;

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

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

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

<?php

$myperson = new Person()

If you would like to allow an object to be instantiated with default values you can allow for this using a default constructor as represented in the following example.

<?php

class Person {
  private $name;

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

##Type Introspection

PHP comes with some functions to test the type of a given variable, and they all start with is_. For example, to test that a variable is an integer, one can invoke is_int() and it will return true or false.

How can we test that an object is a certain 'type' of object? PHP provides an is_a function that takes as its first parameter the object in question, and as a second parameter a string of the class you wish to test against.

###Exercise:

  1. Using the class from Exercise 2, create a constructor function that takes a $name parameter and assigns that value to the name property.

  2. Test that the 'person' object is an instance of the 'Person' class.

  3. Add 'height' and 'haircolor' to your constructor.