Setters in PHP
A setter method is used to modify the value of a private or protected property within a class. It allows controlled access to the internal state of an object by providing a way to update its properties. Setters typically have names prefixed with “set.”
Example: Here, the setName method is a setter that updates the value of the private $name property.
PHP
<?php class Person { private $name ; public function setName( $newName ) { $this ->name = $newName ; } public function getName() { return $this ->name; } } // Usage of the setter and getter $person = new Person( "John Doe" ); $person ->setName( "Jane Doe" ); echo $person ->getName(); ?> |
Output
Jane Doe
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.