Can function __construct() destruct itself after construction?
Like in following pseudo-code, and if yes than how to do it:
function __construct() {
if($something) echo "OK!"
else __destruct();
}
Method __destruct is a magic method in PHP and must not be called manually.
Hovewer it does not do any real magic, the name of the method should be something like onDestructed or so, just like an event listener.
So, __destruct is called when there are no more references to the object. The implementation of method could be the following:
function __destruct(){
echo "An object of class " . __CLASS__ . " has been destroyed " ;
}
And to answer your question, yes, it can be called explicitly, and you will just execute the code inside method __destruct, but you will not destroy the object (unless you do some real garbage collection inside it).
function __construct($something) {
if($something)
echo "OK!" ;
else
$this->__destruct(); // $this-> must be used here!
}
To destroy it, you can use unset($object) or just set it to null in some cases.
unset? Are they other ways of removing object? Im afraid that my poor OOP skills will suffocate memory so that am just in case removing all objects I dont need later.If you destroy the object in constructor then u can achive your require ment like below.
class class1
{
function __construct()
{
print "constructor\n";
print "Now destructor going to call\n";
unset($this);
}
function __destruct()
{
print "this is destructor\n";
}
}
$obj=new class1;
In the above example . While creating object it will call the constructor then constructor function destroy itself by unset function then destructor function called and object also destroyed.
__destruct()? 3) WHY!?!?! 4) Wut? Why?Fatal error: Call to undefined function __destruct() in...throwup in that case @ulkas