Thirupathi
Joined: 01 Dec 2009 Posts: 116
|
Posted: Wed Feb 10, 2010 3:32 am Post subject: Constructors in php |
|
|
Hi Ravisankar,
Constructor:
--------------
Constructor is special function in a class that is automatically called when you create new instance of class with new key word.If class has no constructor then the constructor of base class is being called.
Constructor can take arguments,these arguments can be optional which makes them much more useful.
<?php
class Test{
function Test($name = "Defalult Employee Name",$no = "Default Employee No"){
$this->empName = $name;
$this->empNo = $no;
}
function disply(){
echo $this->empName ."<br />";
echo $this->empNo ."<br />";
}
}
$obj1 = new Test(); //here we are calling default constructor.
$obj1->disply();
$obj2 = new Test("Employee1",101); //here we are calling argumented constructor with two values.
$obj2->disply();
$obj3 = new Test("Employee2"); //here we are calling argumented constructor with one value.
$obj3->disply();
?>
constructor function name must be as class name but in php5 unified constructor is available.so that we can use __construct() instead of using the class name.
You can go through that example i think you may get clarity about your dobht.
Thanks & Regards,
Thirupathi.J |
|