In simple terms, a getter in PHP is simply a method that allows other parts of your code to access a certain class property.
For example:
<?php
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
// Getter
public function getName() {
return $this->name;
}
}
$bob = new Person('Bob');
echo $bob->name; // Bob
?>
A method may not necessarily be designed to just return a property though; you can create other methods so that your class can do funky things.
To expand on the above example, let's give the Person
class a method called say()
, and give it a function/method parameter representing what to say:
public function say($what) {
printf('%s says "%s"', $this->name, $what);
}
And call it after we create an object out of the class:
$bob = new Person('Bob');
echo $bob->name, "\n"; // Bob
$bob->say('Hello!'); // Bob says "Hello!"
Notice that inside the say()
method I refer to $this->name
. It's OK, since the $name
property is found in the same class. The purpose of a getter (and its corresponding setter if any) is to allow other parts of your code to access this property.