What are getters and setters methods in PHP?

PHPServer Side ProgrammingProgramming

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();
   echo $person->name;
?>

Output:

PHP Error Cannot access private property Person::$name

Explanation:

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();
   echo $name;
?>

Output:

welcomeAlex

Explanation:

Here to give access to our private properties, we have made a "getter" function called getData, again because the visibility of the properties is set to private, you will likewise unable to change or modify their values. So, you should utilize one of the "setter" functions that we made: setName. After that, we have Instantiated our Person object.

We "set" the $name property to "Alex " utilizing our setter technique setData. Then We retrieved the value of the $name property by using our getter function getData.

raja
Updated on 31-Dec-2019 08:57:06

Advertisements