PHP Class and Object
In PHP, classes and objects allow you to model real-world entities and define reusable behaviors in a structured way.
PHP में class और object का उपयोग करके आप वास्तविक दुनिया की चीज़ों को model कर सकते हैं और reusable functions बना सकते हैं।
Example 1: Basic Class and Object
<?php
class Employee {
public $name;
public $age;
public $salary;
}
$emp1 = new Employee();
$emp1->name = "Aryan";
$emp1->age = 25;
$emp1->salary = 50000;
echo "Name: $emp1->name\n";
echo "Age: $emp1->age\n";
echo "Salary: ₹$emp1->salary";
?>
Name: Aryan
Age: 25
Salary: ₹50000
Example 2: Constructor
<?php
class Employee {
public $name, $age, $salary;
function __construct($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
function display() {
echo "Name: $this->name, Age: $this->age, Salary: ₹$this->salary\n";
}
}
$emp = new Employee("Sita", 28, 70000);
$emp->display();
?>
Name: Sita, Age: 28, Salary: ₹70000
Example 3: Bonus Method
<?php
class Employee {
public $name, $salary;
function __construct($name, $salary) {
$this->name = $name;
$this->salary = $salary;
}
function addBonus($amount) {
$this->salary += $amount;
}
function show() {
echo "Employee: $this->name, Final Salary: ₹$this->salary\n";
}
}
$emp = new Employee("Kiran", 80000);
$emp->addBonus(5000);
$emp->show();
?>
Employee: Kiran, Final Salary: ₹85000
Example 4: Private Variables
<?php
class Employee {
private $name, $age, $salary;
function __construct($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
function getDetails() {
return "Name: $this->name, Age: $this->age, Salary: ₹$this->salary";
}
}
$emp = new Employee("Anjali", 32, 95000);
echo $emp->getDetails();
?>
Name: Anjali, Age: 32, Salary: ₹95000
Example 5: Multiple Employees
<?php
class Employee {
public $name, $age, $salary;
function __construct($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
function show() {
echo "Name: $this->name | Age: $this->age | Salary: ₹$this->salary\n";
}
}
$employees = [
new Employee("Amit", 26, 40000),
new Employee("Priya", 29, 55000),
new Employee("Vikram", 31, 62000)
];
foreach ($employees as $emp) {
$emp->show();
}
?>
Name: Amit | Age: 26 | Salary: ₹40000
Name: Priya | Age: 29 | Salary: ₹55000
Name: Vikram | Age: 31 | Salary: ₹62000