What are constructor and destructor in PHP ?
- Sharad Jaiswal
- 24th Mar, 2020
1 answer(s) :
-
Reply
"
In PHP there are two special functions known as constructor and destructors which are used for creating and destroying an object respectively. A constructor is used mostly for sending parameters and creating any new object.
Example
class Animal { public $name = "No-name animal" ; public function _construct() { echo "I 'm alive!"; } }
For constructing a new object in the above code we will use the Coding line
$animal = new Animal();
The result that we will get is
<?php class Animal { public $name = "No-name animal" ; public function _construct($name) { $this- >name = $name; } } $animal = new Animal ( "Bob the Dog") ; echo $animal- >name; ? >
In the case of destructor
For the same example, if you want to dispose of an object then you need to do it manually. The object will get destroyed automatically which is not needed.
<?php class Animal { public $name = "No-name animal" ; public function _construct($name) { echo "I 'm alive!"; $this- >name = $name; } public function _destruct () { echo "I 'm dead now : (" ; } } $animal = new Animal("Bob") ; echo "Name of the animal: " . $animal- >name; ? >
Post your Answer :
Valid name is required.
Valid name is required.
Valid email id is required.
Anug Verma
15th Feb, 2020