Getters in PHP
A getter method is responsible for retrieving the value of a private or protected property within a class. It allows external code to access the property’s value without directly manipulating it. Getters typically have names prefixed with “get.”
Example: Here, the getName method is a getter that returns the value of the private $name property.
PHP
<?php class Person { private $name ; public function __construct( $name ) { $this ->name = $name ; } public function getName() { return $this ->name; } } // Usage of the getter $person = new Person( "John Doe" ); echo $person ->getName(); ?> |
Output
John Doe
In this example, .
What are getters and setters methods in PHP ?
In object-oriented programming, getters and setters are methods used to access and modify the private or protected properties of a class. These methods provide a controlled way to retrieve and update the values of class properties, promoting encapsulation and maintaining the integrity of an object’s state.