|
Constructor: Guardian angel of a Class |
Keywords
|
The role of the constructor is to
check on the class once it is instantiated. The function __constructor will
run as soon as the instance is created. If you don't create a constructor
function, there will be default constructor created.
Once object is created, it should be
destroyed. The fourth generation programming languages destroy unused
object, often referred as "Garbage Collection". You can enforce this
|
<? class test { function testfunc($value) { echo "<font color='red'>testfunc Calling function construct </font><br>" ; $this->__construct(); register_shutdown_function(array($this,"__destruct")); echo " Class testfunc runtime $value <br>"; } function __construct() { echo "Constructor Evoked <br>"; } function __destruct() { echo "responding function destruct<br>"; echo "Free Memory <br>"; } }; echo "<font color='red'><b>Load program :</b></font><br>"; $t=new test(); echo "Class Instance created <br>"; $t->testfunc(5);
?>
|
- In the
above example, you will notice that when you create an object with the
keyword "new", the compiler looks for the constructor first .
- Now after an object is
created, when you are using the object, as shown below
- t is the
object, a pointer "->", and a function with a parameter 5
"testfunction(5)" .
- again the
constructor was evoked.
- Once object is done
with his designated task, it is time to destroy the object. In the above
example constructor was called twice, and destroyed twice.
|
 |
| |