349 of 410 menu

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

public 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 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:

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

Example

Using __set for data validation before assignment:

<?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:

100

See Also

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