Constructors and deconstructors in PHP. Code example open

Constructors and deconstructors in PHP. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

__construct – specail method(function) which is performed when creating a class object and serve for initial initialization of its properties.

To create a constructor, you must declare a function named __construct:

<?php

class Person {

    public $name, $age;
    
    public function __construct($name, $age) {
    //pass the properties $name and $age to the properties of the constructor
        $this->name = $name;
        $this->age = $age;
    }

    public function displayInfo() {
        echo "Name: $this->name; Age: $this->age<br>";
    }
}

$tom = new Person("Tom", 36);
$tom->displayInfo();//Name: Tom; Age: 36

$bob = new Person("Bob", 41);
$bob->displayInfo();//Name: Bob; Age: 41

?>

Constructor can get default properties:

<?php
function __construct($name="Billy", $age=33)
{
    $this->name = $name;
    $this->age = $age;
}
//if we pass properties to an object, standard properties are used
$one = new Person();// Billy; 33
$two = new Person("Willy", 34);// Willy, 34
?>

Creating properties through the constructor (PHP 8+):

<?php
class Person
{ 
    function __construct(public $name, public $age) {
        $this->name = $name;
        $this->age = $age;
    }
}
?>

When declaring properties like this, you can also pass default values to them:

function __construct($name = "Sam", public $age = 33)

!You can combine both ways of declaring variables

Destructors

Destructors are used to free resources used by the program – to free open files, open
database connections, etc. An object’s destructor is called by the PHP interpreter itself after the last reference is lost
to this object in the program.

Destructors are created using the __destruct function:

<?php
//when the object is no longer referenced in the program, it will be destroyed and the destructor will be called.
function __destruct()
{
    echo "Destructor";
}
?>
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation