← Back to Chapters

PHP OOP Getter Method

? PHP OOP Getter Method

? Quick Overview

A getter method in PHP Object-Oriented Programming is used to safely retrieve the value of a private or protected property from a class.

? Key Concepts

  • Getter methods start with the prefix get
  • They protect class data using encapsulation
  • They allow validation or formatting before returning values

? Syntax / Theory

Instead of accessing properties directly, PHP encourages the use of methods to control how data is accessed from outside the class.

? Code Example

? View Code Example
// Define a class with private property and getter method
name = $name;
}

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

$obj = new Student();
$obj->setName("Meghraj");
echo $obj->getName();
?>

? Live Output / Explanation

The getter method getName() returns the value of the private property $name, allowing safe read-only access.

? Interactive Explanation

This flow demonstrates encapsulation:

  • Value is set using a setter
  • Private property remains hidden
  • Value is retrieved using a getter

? Use Cases

  • Reading user profile data securely
  • Formatting values before returning
  • Maintaining data integrity in large applications

✅ Tips & Best Practices

  • Always keep properties private
  • Getter methods should return values, not echo them
  • Use meaningful method names like getName()

? Try It Yourself

  • Create a Car class
  • Add a private property $brand
  • Create setBrand() and getBrand()
  • Set and retrieve the brand using methods