The __set() magic method allows us to intercede in setting the properties within the class.

You should already know the simple way of setting the properties of a class externally likeso,

class DevPeel
{
	//
}

$class = new DevPeel();
$class->name = 'devpeel';

var_dump($class);

If we run it, it’ll show

object(DevPeel)#1 (1) {
  ["name"]=>
  string(7) "devpeel"
}

Another Example

Let’s take a look at how we set data in our class or the more common way of doing so.

class User
{
	protected $data = [
		'email' => '[email protected]'
	];

	public function setEmail($email){
		$this->data['email'] = $email;
	}
}

$user = new User();

$user->setEmail('[email protected]');

var_dump($user);

Upon running this piece of code, it’ll surely set the new email for us but if you notice we’ve to use custom functions for each of stuff we’d require to update in our data collection, which isn’t the appropriate solution. What we can else do is replace the setEmail function to more generic likeso,


class User
{
	protected $data = [
		'email' => '[email protected]'
	];

	public function set($key, $value){
		$this->data[$key] = $value;
	}
}

$user = new User();

$user->set('email','[email protected]');

var_dump($user);

That’s still not clean enough. what we really need is to set email by simply $user->email = '[email protected]' and we can achieve it by __set() magic method.

class User
{
	protected $data = [
		'email' => '[email protected]'
	];

	public function __set($key, $value){
		$this->data[$key] = $value;
	}
}

$user = new User();

$user->email = '[email protected]';

var_dump($user);

Another Example (Overriding Constructor Data)

class User
{
	protected $data = [];

	public function __construct($data){
		$this->data = $data;
	}

	public function __set($key, $value){
		$this->data[$key] = $value;
	}
}

$user = new User([
	'email'=>'[email protected]',
	'name'=>'usama muneer'
]);

var_dump($user);

$user->email = '[email protected]';

var_dump($user);

In this example, we’re passing the dataset into our constructor and then overriding email property using __set() magic method. Below is the result from before & after overriding.

object(User)#1 (1) {
  ["data":protected]=>
  array(2) {
    ["email"]=>
    string(17) "[email protected]"
    ["name"]=>
    string(12) "usama muneer"
  }
}
object(User)#1 (1) {
  ["data":protected]=>
  array(2) {
    ["email"]=>
    string(18) "[email protected]"
    ["name"]=>
    string(12) "usama muneer"
  }
}

You may also Like