PHP object construct


A constructor is a special method in a class. When you use the new operator to create an instance of a class, the constructor will be called automatically and its name must be __construct().

In a class can only declare a constructor, but only in the creation of each object will be called when a constructor, can not be active call this method, it is usually used to perform some useful initialization tasks. The method has no return value.

grammar:

function __construct(arg1, arg2, ...)
{
    ...
}

example:

class Person {
    var $name;
    var $age;

    // Define a constructor initialization assignment
    function __construct($name, $sex, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    function say() {
        echo "My name is: ". $this->name. "<br />";
        echo "My age is: ". $this->age;
    }
}

$p1 = new Person("David", 20);
$p1->say();

Run the example and output:

My name is David
The age is

In this example, the object properties are initialized with the constructor.


Tip

PHP does not automatically call the constructor of the superclass in the constructor of this class. To execute the constructor of the parent class, you call parent::__construct() in the constructor of the subclass.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook