Methods are the functions defined within the class. They work within the environment of the class, including its variables. For classes, there is a special method called a constructor that's called when a new instance of a class is created to do any work that initializes the class, such as setting up the values of variables in the class. The constructor is defined by creating a method that has the same name as the class. Creating the Test constructor
<?php class Test { // Constructor function Test() { } } ?>
PHP 5 supports a new syntax for creating a constructor method using _ _construct
<?php class Test { // Constructor >__construct(){ } } ?>
When you declare a new instance of a class, the user-defined
constructor is always called, assuming that one exists. As you know, a class
provides the blueprint for objects. You create an object from a class. If you
see the phrase "instantiating a class," this means the same thing as creating an
object; therefore, you can think of them as being synonymous. When you create an
object, you are creating an instance of a class, which means you are
instantiating a class.
The new operator instantiates a class by allocating
memory for that new object, which means that it requires a single, postfix
argument, which is a call to a constructor. The name of the constructor provides
the name of the class to instantiate, and the constructor initializes the new
object.
The new operator returns a reference to the object that was created.
Most of the time, this reference is assigned to a variable of the appropriate
type. However, if the reference is not assigned to a variable, the object is
unreachable after the statement in which the new operator finishes
executing.