How to create new property dynamically

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

Here's an example:

<?php

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).

Watch a course Learn object oriented PHP

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

<?php

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

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

It is important to notice that the __set method is called when you try to access a property that doesn't exists, so you can use that magic method to make sure that your property is created if it doesn't exist yet.