Constructors and Destructors

Examples:
using new unified constructors

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.

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}
 
class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}
 
class OtherSubClass extends BaseClass {
    // inherits BaseClass's constructor
}
 
// In BaseClass constructor
$obj new BaseClass();
 
// In BaseClass constructor
// In SubClass constructor
$obj new SubClass();
 
// In BaseClass constructor
$obj new OtherSubClass();
?>
Constructors in namespaced classes

Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

1
2
3
4
5
6
7
8
9
<?php
namespace Foo;
class Bar {
    public function Bar() {
        // treated as constructor in PHP 5.3.0-5.3.2
        // treated as regular method as of PHP 5.3.3
    }
}
?>
Destructor Example

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }
 
   function __destruct() {
       print "Destroying " $this->name . "\n";
   }
}
 
$obj new MyDestructableClass();
?>
doc_php
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.