__construct in PHP: What It Is and How It Works
__construct in PHP is a special method called a constructor that runs automatically when you create a new object from a class. It is used to set up or initialize the object with default values or actions right away.How It Works
Think of __construct as the setup routine for a new object. When you create an object from a class, PHP looks for this method and runs it automatically. This is like when you buy a new phone and it turns on with some default settings ready for you.
This method can take inputs (called parameters) to customize the object as it is created. For example, if you have a class for a car, the constructor can set the car's color or model right when you make the car object.
Without a constructor, you would have to set these properties manually after creating the object, which can be less convenient and error-prone.
Example
This example shows a class with a __construct method that sets the name of a person when the object is created.
<?php class Person { public $name; public function __construct($name) { $this->name = $name; } public function greet() { return "Hello, my name is " . $this->name . "."; } } $person = new Person("Alice"); echo $person->greet();
When to Use
Use __construct whenever you want to make sure your object starts with certain values or settings immediately after creation. This is very common in real-world programming to avoid forgetting to set important properties.
For example, if you build a shopping cart class, you might use the constructor to start with an empty list of items. Or if you create a database connection class, the constructor can open the connection right away using given credentials.
It helps keep your code clean and your objects ready to use without extra setup steps.
Key Points
__constructis a special method called automatically when an object is created.- It is used to initialize object properties or run setup code.
- It can accept parameters to customize the object at creation.
- Using constructors makes your code cleaner and safer.
Key Takeaways
__construct runs automatically to set up new objects in PHP classes.