The __set() Method – Writing Inaccessible Properties

This entry is part 2 of 4 in the series Magic Methods in PHP

The __get() method is called when data from an undeclared/inaccessible property is to be read. The __set() magic method complements the __get() method. The __set() method is called when data is to be assigned to an inaccessible property of a class.

class Employee {

public $name;

private $_values = array();

public function __set($name, $valuel) {

$this->_values[$name] = $value;

}

public function __get($name) {

return $this->_values[$name];

}

}

$empObject = new Employee();

// Assigning value to public variable

$empObject->name = 'Refulz';

$empObject->designation = 'Manager';

echo $empObject->designation;

The Employee class has no designation property. But, when the code tries to set value from the class object, the __set() method is called automatically. The __set() method accepts two parameters i.e. the name of the property and the passed value.

Any logic can be written in the __set() method to handle the received data. In our case, we are creating new variable to save the passed value.

You may also code the __set() to raise an exception when someone tries to set value for an undefined property.

class Employee {

public $name;

private $_values = array();

public function __set($name, $value) {

throw new Exception('Cannot assign values to undefined properties',1);}

public function __get($name) {

return $this->_values[$name];

}

}

$empObject = new Employee();

// Assigning value to public variable

$empObject->name = 'Refulz';

$empObject->designation = 'Manager';

echo $empObject->designation; // Exception Message

__set() Magic for Calling Methods

The __set() method can also be used for wrapping methods. I am using the same __get() example to illustrate how it will work with __set() instead.

 Class Employee {

function __set( $property, $value ) {

$method = "set{$property}";

if(method_exists( $this, $method  ) ) {

return $this->$method($value);

}

}

function setName($value) {

// Some Logic here

}

$empObject = new Employee();

// Assigning value to public variable

$empObject->name  = 'Refulz';

}

When the $empObject->name = 'Refulz' is called, it checks whether $name exists as a public member of the object. Since, it doesn’t exist, __set() method will be called. Since, we have used method_exists() in __set(), we can execute a call equivalent to $empObject->setName('Refulz').

Since, PHP function and method calls are not case sensitive, so not to worry about camelCasing.

We will learn about overloading and accessor and mutator functions.

Series Navigation<< The __toString() Method – Objects as StringsThe __call Method – Call Inaccessible and Non-existent Methods >>