PHP Free Tutorial

Setters and Getters in PHP

In OOP, PHP, Programming by Baqir Ali

What are Setter and Getter Methods?

When we declare the class members as private then we will not be able to access them from outside the class. Therefore we use setters and getters to assign and retrieve values of the private members.

What is a setter/Mutator?

We use the setter method to assign/set values of the private members.

What is a getter/Accessor?

We use the getter method to get/retrieve the values of the private members.

Examples of Setters and Getters.

	class Bank
		private $accountN;
		private $amount;
                // set methods or mutators
		function setAccountNo($accN)

		function setAmount($am)
                // get methods or accessors
		function getAccount()
			return $this->accountN;

		function getAmount()
			return $this->amount;
	$bank=new Bank();

	echo "<br> Account No is : ".$bank->getAccount();
	echo "<br> Current balance is : ".$bank->getAmount();



Account No is: 12-ABCd-1231
Current balance is: 100000

In the above example, there is a class called Bank that has two private members account and amount. As both members are private we can not use them outside class Bank therefore we are using setters to set values for them and getter to get their values.

Support us by sharing this post