Broad Network


Constructors and Destructors in PHP

Classes and Objects in PHP - Part 2

Foreword: In this part of the series, I talk about Constructors and Destructors in PHP.

By: Chrysanthus Date Published: 24 Nov 2018

Introduction

This is part 2 of my series, Classes and Objects in PHP. In this part of the series, I talk about Constructors and Destructors in PHP. You should have read the previous part of the series before coming here, as this is the continuation.

Construction without Constructor
Construction means, creating an object from a class. Read and test the following code:

<?php

    class Calculator
        {
            public $num1;
            public $num2;

            public function add()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }
        }

        $myObject = new Calculator();
        $myObject->num1 = 2;
        $myObject->num2 = 3;
        $result = $myObject->add();
        echo $result;

?>

The output is:

    5

In the code, the constructor call is,

    Calculator()

a function call. There is no explicit constructor function definition, in the code.

Explicit Constructor
In PHP, the syntax for the explicit constructor is:

    void __construct ([ mixed $args = "" [, $... ]] )

You code this statement in the class definition (description). Try the following code:

<?php

    class Calculator
        {
            public $num1;
            public $num2;

            function __construct()
                {
                }

            public function add()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }
        }

        $myObject = new Calculator();
        $myObject->num1 = 2;
        $myObject->num2 = 3;
        $result = $myObject->add();
        echo $result;

?>

The output is:

    5

The class definition now has 2 functions, whose names are __construct and add() . The constructor, __construct() governs the constructor call, Calculator() .

You can place initialization code in the constructor function block.

Default Values and Initialization
Try the following code, where any object instantiated (created) already has default values:

<?php

    class Calculator
        {
            public $num1 = 2;   #default value
            public $num2 = 3;   #default value

            public function add()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }
        }

        $myObject = new Calculator();
        $result = $myObject->add();
        echo $result;

?>

The output is:

    5

The problem with the above code is that, for every object created, you have the same initial values. If you want different instantiated objects to have different initial values, then use the constructor, with arguments, as the following code illustrates:

<?php

    class Calculator
        {
            public $num1;
            public $num2;

            function __construct($param0, $param1)
                {
                    $this->num1 = $param0;
                    $this->num2 = $param1;
                }

            public function add()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }
        }

        $myObject = new Calculator(2, 3);
        $result = $myObject->add();
        echo $result;

?>

Note how the constructor has been defined. Also note how it has been called with, "Calculator(2, 3)". The output is:

    5

This code shows how to crreate an object with initialization.

Destructor
A destructor, destroys an object and so frees memory, to be used by other tasks. If you do not destroy an object, when it is no longer needed, it will be destroyed by PHP.  However, in the destruction process, you may want to tidy up certain things - in this case you will have to code the destructor. The syntax to destroy an object is:

    void __destruct ( void )

Read and test the following code:

<?php

    class MyDestructableClass
        {
            function __construct()
                {
                    print "In constructor<br>";
                }

            function destroy()
                {
                    function  __destruct()
                        {
                            print "Destroying " . __CLASS__ . "n";
                        }

                    __destruct();    //the call to destroy
                }
        }

    $obj = new MyDestructableClass();
    echo 'seen' . '<br>';
    $obj->destroy();

?>

The output is:

    In constructor
    seen
    Destroying MyDestructableClass

That is it for this part of the series, we stop here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

BACK NEXT

Comments