i
PHP Variables
PHP Data Types
PHP Echo & Print
PHP Strings
PHP Numbers
PHP Constants
PHP Operators
PHP if...else...elseif Statements
Switch Statement
PHP Loops
PHP Arrays
Superglobals
PHP Coding Standards
PHP Form Handling
PHP Form Validation
PHP URLs Validation
PHP Form Required Validation
Complete Form Example
PHP File Functions Open/Read
PHP File Create/Write
PHP File Upload
PHP Cookies Handling
PHP Session Handling
PHP filter_var() Function
PHP Validation Filters
PHP Sanitization Filters
Using Filters
Filters Advanced
JSON
PHP Date and Time
MySQL Database
MySQL Connect
MySQL Commands-Creating a Table
MySQL Commands-Inserting The data
MySQL Commands-Prepared Statement
MySQL Commands-Selecting The Data
MySQL Commands-Where and Order By
MySQL Commands-Deleting And Updating The Data
PHP-OOP Introduction
PHP-Classes/Objects
PHP-Constructor/Destructor
PHP-Access Modifiers
PHP-Inheritance
PHP-Inheritance and Protected Access Modifier
PHP-Overriding Inherited Methods
PHP-Final keyword
PHP-Abstract Classes
PHP-Constants
PHP-Traits
PHP-Static Methods and Properties
Introduction to Functions
Defining A function
Returning Values From A Function
Dynamic Function Calls
Variable Scope
Understanding Arguments Or Parameters
Testing For A Function Existence
Returning Multiple Values From A Function
Making practical Use By Building Code Libraries For Code Re-usability
Using Include() And Require()
Like other languages, Constructor allows us to initialize the properties of an object when you create it. You can use constructor in PHP by using __construct() function that starts with two underscores. PHP calls the function automatically whenever an object is created from a class and you can also define parameters for this function. It saves our time and effort to call a function example to set the values for the properties.
For example:
class Cars {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$Mercedes = new Cars("Mercedes", "red");
echo $Mercedes->get_name();
echo "
";
echo $Mercedes->get_color();
?>
The __construct() function runs with the name and color attribute specified while creating the object. Set function runs automatically and sets the value for the newly created object.
A destructor is used when the script is stopped, or you exit from the script and objects are destructed. You can use __destruct() function to let PHP automatically call the function at the end of the script to destruct the object.
class Cars {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The Car name is {$this->name}.";
}
}
$Swift = new Cars("Swift");
?>
We have only created the object with the name value, but the construct function and destruct function will run automatically and print the output as below:
The Car name is Swift.
Don't miss out!