What are getters and setters?

What are getters and seters in PHP5?

Can someone give me a good example with an explanation?

+4
source share
4 answers

This is the concept of data hiding (or encapsulation) in OOP. For example, if you want to have a specific property in your class, say โ€œAmountโ€ and give the client of your class the ability to change or retrieve its value. You must make your Sum variable private (not visible to those using your class) and generate two methods: getter and setter, which manipulate your value (public).

The reason is to be able to check or manipulate the data before setting or getting your value. Here is a quick example:

class test { private $count; //those who use your class are not able to see this property, only the methods above public function setCount( $value ) { //make some validation or manipulation on data here, if needed $this->count = $value; } public function getCount() { return $this->count; } } 
+8
source

Class attributes can be private. This means that only an object can read and write its own private attributes. Therefore, you need methods to do this. Methods that read and return the value of an attribute are called getters, and those that write attributes are called setters. Using these methods, classes can control what happens and what happens. This concept is called encapsulation .

+3
source

Getters and Setters is a completely new concept in PHP 5 in the form of two magic functions __get () and set (). These two functions set or get the value of an object property, as described in the following example.

 class Datatype{ private $thing; public function _set($k,$v){ $this->$k = $v; } public function __get($k){ return $this->$k; } } 
+2
source

The PHP manual is not really a very detailed account of this problem, but there is a very detailed example that should explain a lot. Magic Methods: Property Overloading

+1
source

Source: https://habr.com/ru/post/1301736/


All Articles