What are getters and setters methods in PHP?

In this article, we learn the best way to create getter and setter strategies in PHP. Getter and setter strategies are utilized when we need to restrict the direct access to the variables by end-users. Getters and setters are methods used to define or retrieve the values of variables, normally private ones.

Just as the name suggests, a getter method is a technique that gets or recovers the value of an object. Also, a setter method is a technique that sets the value of an object.

Example

Let's understand the use of getter and setter methods through an example.

<?php
class Person{
private $name; public function setName($name){
$this->name =$name;
}
public function getName(){
return $this->name; } }$person = new Person();

In our Person class above, we have a private property called $name. Because it is private property, we are unable to access them directly like the above and that will produce a fatal error. Example To run the code above and get our desired output Let's test this example. <?php class Person{ private$name;
public function setName($name){$this->name = $name; } public function getName(){ return 'welocme'.$this->name;
}
}
$person = new Person();$person->setName('Alex');
$name =$person->getName();