Home Tutorials Constructor

Constructor

  previous next
March 08, 2009 by Victor    

All classes have a special built-in method called 'constructor' that you don't need to expicitly define. Constructors can help with object initialization, you just pass values to the constructor method when you instantiate a class (with the “new” keyword) to set automatically object’s member properties.

Note that every class can only have a single constructor, the constructor function in PHP is called __construct(). However, this is for PHP5, in PHP4 the constructor used to have the same name as the class.

The next example shows how to use the constructor method.

<?
class User 
{
    ### properties 
    var $name;
    var $username;
    var $email;
    var $id = 1000;
 
    ### methods 
    # constructor
    function __construct($newname,$lastid) 
    {
       $this->name = $newname;
       $this->id = ++$lastid;
    }
 
    function setname($newname) 
    {              
       $this->name = $newname;           
    }
 
    function getname()
    {
       return $this->name;
    }
} 
 
### create users
$admin = new User("harris",0);
$auser = new User("gers",$admin->id);
$buser = new User("mcbrain",9);
$buser->setname("smith");
 
print "\n $admin->name $admin->id";
print "\n $auser->name $auser->id";
print "\n $buser->name $buser->id";
?>

Similar to the constructor is the destructor function __destruct() that is responsible for the object's disposal. See it as the final actions before an object falls into the shadows.

Add comment


Security code
Refresh