In PHP, classes and objects are the foundation of Object-Oriented Programming (OOP). A class defines the structure (properties and methods), and an object is an instance of that class.
1. Create a Class
class Car {
public $brand = "Toyota"; // Property
public function honk() { // Method
return "Beep beep!";
}
}
2. Create an Object
$myCar = new Car(); // Create object
echo $myCar->brand; // Access property → Toyota
echo $myCar->honk(); // Call method → Beep beep!
3. Add a Constructor
class User {
public $name;
public function __construct($userName) {
$this->name = $userName;
}
public function greet() {
return "Hello, " . $this->name;
}
}
$user = new User("John");
echo $user->greet(); // Output: Hello, John
File: user_class.php
4. Class with Multiple Properties and Methods
class Product {
public $name;
public $price;
public function setDetails($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getDetails() {
return "Product: {$this->name}, Price: ₹{$this->price}";
}
}
$p = new Product();
$p->setDetails("Laptop", 45000);
echo $p->getDetails();
File: product_class.php
5. Access Modifiers (Public, Private, Protected)
class Account {
private $balance = 1000;
public function getBalance() {
return $this->balance;
}
}
$acc = new Account();
echo $acc->getBalance(); // Output: 1000
File: account_class.php
Summary Table
Concept | Syntax | Purpose |
---|---|---|
Class | class ClassName {} |
Define blueprint |
Object | $obj = new ClassName(); |
Create instance of class |
Property | public $x; |
Variable inside class |
Method | public function doSomething(){} |
Function inside class |
Constructor | __construct() |
Run when object is created |
Access Modifiers | public , private , protected |
Control access to class members |