Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Constructor

The constructor is a magic method in a class, which is called at instantiation of an object, with the provided arguments. It is called __construct.

The constructor is an optional method: a class may be created without it. Though, it is very common to have it.

Parent’s constructor are not automatically called, when a child class defines a constructor. They have to be called explicitly.

When a class has a parent, with a constructor, and not constructor itself, then the parent constructor is automatically called, by inheritance.

A constructor may have a visibility, and be not available to the outside. In particular, when creating named constructors, the magic method __construct is usually made private and object instantiation happens in a static method of that same class.

<?php

    class Elephpant {
        private $trunkLength;

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

    $elephpant = new Elephpant(1);

?>

Documentation

See Also