W3docs

How to create new property dynamically

In PHP, you can create a new property for an object dynamically by using the magic method __set.

In PHP, you can create a new property for an object dynamically by using the magic method __set.

Here's an example:

Example of creating a new property for an object dynamically in PHP

<?php

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

$obj = new MyClass();
$obj->newProperty = "Hello World";
echo $obj->newProperty; // Outputs: "Hello World"

In this example, the __set method is used to create a new property on the $obj object called newProperty and assigns it the value "Hello World". The value of the new property can be accessed by using the property name ($obj->newProperty).

You can also use variable variable names to assign values to properties whose names are stored in variables.

Example of using variable names to assign values to properties in PHP

<?php

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

$obj = new MyClass();
$propertyName = 'newProperty2';
$obj->$propertyName = "Hello World";
echo $obj->$propertyName;

Note that __set is triggered only when assigning a value to an undefined or inaccessible property, not when reading it. In PHP 8.2+, dynamic properties are deprecated by default. To use this approach without deprecation warnings, add the #[AllowDynamicProperties] attribute to your class, or store dynamic values in an internal array instead. If you also need to read these dynamic properties, implement the __get magic method.