Translated by Google Translate
Constructor and Destructor in OOP (PHP)
In OOP, you will never separate from constructor and destructor. What is constructor and destructor in OOP? Constructor is special statement (also called special method) that created when an object created (instance of class).
If you didn't create the constructor or destructor in a class then
constructor and destructor automatically created. When you create $objPeople in the previous OOP tutorial, then constructor and destructor automatically created
Normally,
the constructor is created to provide an initial operation to be
performed when an object created (inilization object). This is the
writting format how to create a constructor
function __constructor(parameter) { code } |
Keyword construct should started with double underscore and then give the parentheses (). Among the parentheses, you can give the parameter if you think you need to add parameter. Then you can build your code in constructor.
Eg you create class product, in that class include property of quantity that the initialize value shuld be 0, then the code will look like below :
class barang { private name; private price; private quantity; function __construct() { $this->quantity = 0; } } |
If the constructor created and used when the object created, then destructor is the reverse of constructor. Destructor created and used when the object deleted. In PHP programming, destructor automatically called in your final PHP scripting.
Same like constructor, writing format of destructor begin by double underscore. Here it is :
function __destructor(parameter) { code } |
And this another example of constroctor and destructor :
<?php class people { private $name; function __construct($name) { $this->name=$name; echo "Constructor : $this->name created <br>"; } function speaking() { echo "Hallo, my name is ".$this->name." <br />"; } function __destruct() { echo "Destructor : $this->name deleted <br/ >"; } } $people1 = new People("People 1"); $people1->speaking(); $people2 = new People("People 2"); $people2->speaking(); ?> |
And this is the result in browser :
In the picture above, there are six teks, the result from calling the constructor, calling method speaking(), and calling destructor. Though you don't put code call method __construct() & method __destruct(). This happen because when you create an object, it's automatically creating constructor for the object. Then when it has used, it will removed from memory. It's automatically the destructor from that object will be called.
Here is the example of the use constructor, destructor, method, object, and property for calculating the student's grade.
And the looks like in browser is :
Tags: OOP, PHP