Select Page
PHP getter and setter functions

 

GETTER AND SETTER FUNCTIONS EXAMPLE IN PHP CLASSES

 

 

A standard paradigm in object-oriented programming is to use getter and setter methods (class functions) to provide access to the class’ attributes (variables).

In PHP classes too you can easily implement getter and setter methods.

 

Why should you use a method to retrieve or to set a class’ variable instead of directly accessing it?

It’s quite simple.

If you set a class’ attribute as public, then you will have no control over which values the attribute can take. Any external code will be able to change it without any constraint.

 

If you, instead, set the property as private and provide a public method to set its value, you can decide which values to accept and you can perform any type of validation and sanitization before setting the new value. 

In other words, you can implement a filter between the attribute and the code outside of the class.

 

In the following short example, you can see how to implement getter and setter functions in PHP.

In this example, the $name attribute must be between 3 and 16 characters long. The setter function makes sure that the new name’s length is within that range before changing the attribute:

<?php

class MyClass
{
	/* Private attribute, cannot be accessed directly */
	private $name;
	
	/* Constructor */
	public function __construct()
	{
		$this->name = '';
	}
	
	/* Getter function to read the attribute */
	public function get_name()
	{
		return $this->name;
	}
	
	/* Setter function to change the attribute */
	public function set_name($new_name)
	{
		if ($this->is_valid_name($new_name))
		{
			$this->name = $new_name;
		}
	}
	
	/* Checks if the name is valid */
	private function is_valid_name($name)
	{
		$valid = TRUE;
		
		/* Just checks if the string length is between 3 and 16 */
		if (mb_strlen($name) < 3)
		{
			$valid = FALSE;
		}
		else if (mb_strlen($name) > 16)
		{
			$valid = FALSE;
		}
		
		return $valid;
	}
}

$mc = new MyClass();
$mc->set_name('Alex');
echo $mc->get_name();

 

 

If you have any questions, feel free to ask in the comments below or on my Facebook Group: Alex PHP café.

If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!

 

Alex