minte9
LearnRemember / PHP



Contruct

Php uses the magic __construct() method as constructor. Constructor is usefull for initializing object's properties.
 
class A 
{
    function __construct() 
    {
        echo __METHOD__;
    }
}

$obj = new A(); // A::__construct

Destruct

You can unset() or overwrite a variable that is reference for an object. The object itself may not be destroyed. The reference to it is held elsewhere.
 
class A 
{
    function __construct() {}
    function foo()
    {
        echo "A is alive";
    }
}

$a = new A();
echo $a->foo(); // A is alive

$b = $a;
unset($a);
echo $a->foo(); // Fatal error: ... non-object

echo $b->foo();  // A is alive
The __destruct() method is called at the end of script execution.
 
class A 
{
    function __construct() 
    {
        echo "A is alive";
    }
    
    function __destruct() 
    {
        echo "A is dead";
    }
}

$a = new A(); // A is alive / A is dead






Questions and answers




Which one is the constructor for class foo?

  • a) __construct()
  • b) foo()
  • d) constructor()

When is the destructor of the object $object called?

  • a) When you use unset($obj)
  • b) At he end of the script execution


References





Connected Graph