The __set Magic Method

The magic method __set is automatically called when trying to assign a value to a property that does not exist or is inaccessible in the current context. The method accepts two parameters: the property name and the value being assigned.

Syntax

phppublic function __set(string $name, mixed $value): void

Example

Let's create a class that will use __set to intercept attempts to assign non-existent properties:

php<?php
  class User {
    private $data = [];
    
    public function __set($name, $value) {
      $this->data[$name] = $value;
    }
    
    public function getData() {
      return $this->data;
    }
  }
  
  $user = new User();
  $user->email = 'test@example.com';
  $user->age = 25;
  print_r($user->getData());
?>

Execution result:

phpArray
(
  [email] => test@example.com
  [age] => 25
)

Example

Using __set for data validation before assignment:

php<?php
  class Product {
    private $price;
    
    public function __set($name, $value) {
      if ($name === 'price') {
        if (!is_numeric($value) || $value < 0) {
          throw new Exception('Invalid price value');
        }
        $this->price = $value;
      }
    }
    
    public function getPrice() {
      return $this->price;
    }
  }
  
  $product = new Product();
  $product->price = 100;
  echo $product->getPrice();
?>

Execution result:

php100

See Also

  • the magic method __get,
    which intercepts attempts to read inaccessible properties
  • the magic method __isset,
    which intercepts property existence checks