Current Location: Home> Latest Articles> How to Assign Values to PHP Classes: Constructor and __set() Magic Method Explained

How to Assign Values to PHP Classes: Constructor and __set() Magic Method Explained

M66 2025-10-27

Main Ways to Assign Values to Class Properties in PHP

In PHP object-oriented programming, assigning values to class properties is a common operation. There are two main approaches: assigning values via the constructor during object creation, or dynamically using the __set() magic method after the object is instantiated. The choice depends on your application’s logic and when you need to assign the values.

Assigning Values Using a Constructor

A constructor is a special method in a class that runs automatically when an object is instantiated. By defining parameters in the constructor, you can assign values to properties as soon as the object is created.

class MyClass {
    public $name;

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

$object = new MyClass('John Doe');
echo $object->name; // Outputs "John Doe"

This approach ensures that properties are initialized immediately during object creation, providing better control and maintainability.

Assigning Values Dynamically with the __set() Magic Method

The __set() magic method is automatically triggered when you try to assign a value to an undefined or inaccessible property. This allows for flexible and dynamic property assignments after the object has been created.

class MyClass {
    public function __set($name, $value) {
        $this->$name = $value;
    }
}

$object = new MyClass();
$object->name = 'John Doe';
echo $object->name; // Outputs "John Doe"

This method is useful when property names or values are determined at runtime or depend on external data sources.

Choosing the Right Method

In practice, both constructors and magic methods have their uses:

  • Use a constructor when you want to initialize properties immediately upon object creation.
  • Use the __set() magic method when you need more flexibility to assign properties dynamically after instantiation.

In summary, constructors are ideal for structured, predictable scenarios, while __set() is better suited for dynamic or variable property assignments. Choosing the right method helps keep your PHP code clean, efficient, and maintainable.