Ad Code

Responsive Advertisement

getter and setter in php : Simple Explanation

getter and setter in php  In this composition, we learn the stylish way to produce getter and setter strategies in PHP. Getter and setter strategies are employed when we need to circumscribe the direct access to the variables by end- druggies.

getter and setter in php

getter and setter in php

Getters and setters are styles used to define or recoup the values of variables, typically private bones .

read also : Setter and Getter Python

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

Example

Let's understand the use of getter and setter styles through an illustration.




name = $name;
      }
      public function getName(){
         return $this->name;
      }
   }
   $main = new main();
   echo $main->name;
?>

output:



  PHP Error Cannot access private property main::$name

In our Person class over, we've a private property called$ name. Because it's private property, we're unfit to pierce them directly like the below and that will produce a fatalerror.To run the law over and get our asked affair Let's test this illustration.



  name = $name;
      }
      public function getName(){
         return 'welocme'. $this->name;
      }
   }
   $main = new main();
   $main->setName('US');
   $name = $main->getName();
   echo $name;
?>

output:


welcomeUS

Then to give access to our private parcels, we've made a" getter" function called getData, again because the visibility of the parcels is set to private, you'll likewise unfit to change or modify their values. So, you should use one of the" setter" functions that we made setName. After that, we've expressed our Person object.

Post a Comment

0 Comments

Ad Code

Responsive Advertisement