Class Constructors and Magic Methods

The constructor is a special method, added with PHP 5, that is executed automatically when an object is created. Only one constructor is allowed.

Constructor

The constructor has a special name so that PHP knows to execute the method when an object is created or constructed. Constructors are named __construct (two underscores). They look like normal methods, with the exception that their name is always __construct(), and that they do not have a return statement, as they always have to return the new instance.

function __construct()
{
$this->total = 0; // starts with a 0 total
}

As a constructor is a function, it can use arguments. For example,

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

The key idea behind using a __construct() method is to perform the initial set of executions that need to be done immediately upon object creation.  Hence, you can create instances of the Person class like the following:

$person1 = new Person('John Doe');
echo $person1->name; //prints John Doe

Here, the constructor takes an argument, $username, and assigns it to the $name attribute by accessing it with $this->name.

Magic Methods

There is a special group of methods that have a different behavior than the normal ones. Those methods are called magic methods, and they usually are triggered by the interaction of the class or object, and not by invocations. The magic methods start with __ (two underscores).

__toString()

This method is invoked when we try to cast an object to a string. It takes no parameters, and it is expected to return a string.

__call()

This is the method that PHP calls when you try to invoke a method on a class that does not exist. It gets the name of the method as a string and the list of parameters used in the invocation as an array, through the argument.

__get()

This is a version of __call for properties. It gets the name of the property that the user was trying to access through parameters, and it can return anything.

Destructor

The destructor method, __destruct(), is invoked automatically when an object is destroyed. When we remove an object or perhaps a PHP script ends its execution and releases the memory utilized by the variables, then __destruct() gets called.

class ClassName
{
function __destruct()
{
// function body
}
}

A destructor method does not take arguments.

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive