Comunitatea PHP Romania
 

 
Constructors and Destructors

Constructors and Destructors

Constructor

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Notã: Parent constructors are not called implicitly. In order to run a parent constructor, a call to parent::__construct() is required.

Exemplu 14-1. using new unified constructors

<?php
class BaseClass {
    function
__construct() {
        print
"In BaseClass constructor\n";
    }
}

class
SubClass extends BaseClass {
    function
__construct() {
        
parent::__construct();
        print
"In SubClass constructor\n";
    }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

Destructor

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as Java: When the last reference to an object is destroyed the object's destructor, which is a class method named __destruct() that receives no parameters, is called before the object is freed from memory.

Exemplu 14-2. Destructor Example

<?php
class MyDestructableClass {
    function
__construct() {
        print
"In constructor\n";
        
$this->name = "MyDestructableClass";
    }

    function
__destruct() {
        print
"Destroying " . $this->name . "\n";
    }
}

$obj = new MyDestructableClass();
?>

Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.

Ultimele discutii in forum RSS Forum

Ultimele articole Ultimele articole

Top membri

Pirahna Pirahna
la birou
carco carco
Bucuresti
Birkoff Birkoff
Bucuresti
Mascka Mascka
Braila
raul_ raul_
whooper whooper
Toronto ON
mihaitha mihaitha
Sibiu
gabysolomon gabysolomon
Bacau
oriceon oriceon
Constanta
garlicinicolae garlicinicolae

Newsletter


Email:
 inscriere
 renuntare
 
 Arhiva newsletter

Parteneriat

Copyright © 2001-2008 PHP Romania Add PHPRomania to Google Add PHPRomania to Del.icio.us Add PHPRomania to Stumbleupon Add PHPRomania to Yahoo! Add PHPRomania to Digg Add PHPRomania to Blink Northern Rock | Home Loan | Xbox Mod Chips | Apply for Credit Card | Northern Rock
Ads: Partener Way2Web Nework: gazduire web | inregistrare domenii | web design | imobiliare | web hosting
Powered by Simplis