The __construct Method
The __construct
method is a special class method that is automatically called when creating a new object. It is used to initialize object properties or perform other initial settings. Unlike regular methods, the constructor does not need to be called explicitly.
Syntax
class ClassName {
public function __construct([parameters]) {
// initialization code
}
}
Example
Let's create a simple class with a constructor that sets the $name
property:
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$user = new User('John');
echo $user->name;
?>
Code execution result:
'John'
Example
The constructor can accept multiple parameters and perform complex initialization:
<?php
class Product {
public $id;
public $price;
public function __construct($id, $price) {
$this->id = $id;
$this->price = $price * 1.2; // Adding 20% VAT
}
}
$product = new Product(101, 100);
echo $product->price;
?>
Code execution result:
120
See Also
-
the
__destruct
method,
which is called when an object is destroyed -
the
__clone
method,
which is called when cloning an object