Constructor
- Optionally, define a constructor method
__construct()
to initialize class properties when an object is created. - Constructors are automatically called upon object instantiation.
Example:
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function greet() {
return "Hello, my name is {$this->name} and I am {$this->age} years old.";
}
}
How to Define a Class in PHP?
To declare a class in PHP, we use the keyword class followed by the class name. Class names should follow the CamelCase convention and start with an uppercase letter.