How to create new property dynamically

How to create new property dynamically

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Creating Dynamic Properties in PHP: Magic Methods vs. Arrays

A common request from developers working with object-oriented PHP is the ability to add new properties to an instance after it has been instantiated. You might have a class that represents a generic container or a model where you need to inject data dynamically based on user input or runtime logic. The goal is often simple: define a method like createProperty, pass a name and value, and then access that property directly using the dot notation syntax ($object->hello).

The fundamental constraint here is that PHP's standard type system does not allow you to modify the class definition at runtime to literally add a new member variable declaration. You cannot execute code equivalent to public $hello; inside a method. However, PHP provides two primary mechanisms to achieve this illusion: using arrays as property storage or leveraging magic methods (__get and __set).

The Magic Methods Approach

The most robust way to handle dynamic properties is by utilizing the built-in magic methods __get and __set. This approach allows you to define a consistent interface while keeping your internal data structure flexible.

You can maintain an associative array internally to store these dynamic values:

class Foo {
    protected $user_properties = [];

    public function createProperty($var_name, $val) {
        // Store the value in our internal array
        // This handles both public and private scope logic implicitly
        $this->user_properties[$var_name] = $val;
    }

    public function __get($name) {
        if (isset($this->user_properties[$name])) {
            return $this->user_properties[$name];
        }
        
        // Trigger an error or default value if the property doesn't exist
        throw new ErrorException("Property $name does not exist.");
    }

    public function __set($name, $value) {
        $this->user_properties[$name] = $value;
    }
}

With this implementation, accessing $object->hello triggers the __get method. This satisfies the requirement for dynamic access while allowing you to control permissions. To simulate protected or private behavior without exposing the array directly, you ensure that external code cannot access $this->user_properties unless they know the internal structure. If you strictly want to restrict access, you can add a check in __get to throw an exception if the property isn't found, effectively making it read-only unless you define a setter.

Trade-offs and Performance Considerations

While magic methods solve the syntax problem perfectly, there are significant trade-offs regarding performance and architecture. Every time you access $object->hello, PHP must invoke the __get method. This adds a layer of indirection compared to accessing a real property directly. In high-performance loops or tight cycles where memory access is critical, this overhead can become measurable.

Furthermore, magic methods obscure the actual state of the object. When you inspect an instance using var_dump($object) or debug tools like Xdebug, the dynamic properties won't appear in the standard list unless they are stored in real class members. This makes debugging harder for junior developers who expect to see $hello listed alongside other attributes.

A Better Alternative: The __set_state Pattern or Data Arrays

Before settling on magic methods, consider if you actually need dynamic properties at all. Often, this pattern stems from a desire to model data without strict schema definitions. In many cases, an associative array stored as a private property $data is cleaner and more predictable.

You can expose this data via a dedicated method or use Laravel's Eloquent-style accessors if you are working within that ecosystem. If you are building a generic container class, magic methods are acceptable, but be aware that they complicate serialization (e.g., serialize() might not capture the dynamic properties correctly without explicit handling) and reflection-based introspection.

Conclusion on Implementation

If your use case requires true dynamic property injection for flexibility, the magic method pattern is the standard solution in PHP. It allows you to define a public interface ($object->hello) while managing the underlying storage securely within an array. Just remember to handle missing properties gracefully and be mindful of the performance cost added by every read operation.

For projects requiring strict type safety or complex reflection logic, libraries that implement dynamic property traits or use PHP's ReflectionClass::newInstanceArgs combined with manual property creation might offer a more modern alternative, though those are beyond the scope of simple runtime injection.

Our network