Memory App
Programming
 



Programming > Php > Oop > Class constructor   ZCE 5.3  |  Patterns  |  Modern Php

Contructors

The concept of contructor was already used in PHP 4 (add a method with the name of the class). If you renamed the class you would also have to rename the constructor. Php 5 uses the magic __construct() method as constructor. Constructor is usefull for initializing object's properties.

<?php
    // If the __construct() method is not found, 
    // PHP will look for the old PHP 4-style constructor (foo)

    class foo {

        // PHP 5
        function __construct() {
            echo __METHOD__;
        }

        // PHP 4
        function foo() {
            echo __METHOD__;
        }
    }

    $foo = new foo();
        // output foo::__construct
    $foo->foo();
        // output foo::foo
Destructors When you use 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.

<?php
    class A {
        function __construct() {
        }
        function foo() {
            echo "A is alive";
        }
    }

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

    $b = $a;
    unset($a);

    echo $b->foo();  // A is alive
    echo $a->foo(); // Fatal error: Call to a member function foo() on a non-object
The __destruct() method is called at the end of script execution.

<?php
    class A {
        function __construct() {
            echo "A is alive";
        }
        function __destruct() {
            echo "A is dead";
        }
    }

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


Questions



Top Reference > Programming
0/0 (80)  
Not Logged