B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP PHP Getters and Setters | LiveCodeProgramming

PHP Getters and Setters

Getters and Setters are used to access and update private properties of a class. They help in encapsulating the logic for data access and validation.

Getters और Setters का उपयोग किसी class की private properties को access और update करने के लिए किया जाता है। इससे डेटा को सुरक्षित और validated रखा जा सकता है।

Example using Employee class

This example uses private properties and getter/setter methods for name, age, and salary.

इस उदाहरण में name, age और salary के लिए private properties और उनके getter/setter methods का उपयोग किया गया है।

<?php
class Employee {
  private $name;
  private $age;
  private $salary;

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }

  public function setAge($age) {
    if ($age > 0) {
      $this->age = $age;
    }
  }

  public function getAge() {
    return $this->age;
  }

  public function setSalary($salary) {
    if ($salary >= 0) {
      $this->salary = $salary;
    }
  }

  public function getSalary() {
    return $this->salary;
  }
}

$emp = new Employee();
$emp->setName("Ravi");
$emp->setAge(30);
$emp->setSalary(50000);

echo "Name: " . $emp->getName() . "\n";
echo "Age: " . $emp->getAge() . "\n";
echo "Salary: ₹" . $emp->getSalary();
?>
Name: Ravi Age: 30 Salary: ₹50000