Converting a PHP array to class variables

Converting a PHP array to class variables

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

Stefan Bogdanescu

Founder & Senior Architect

Converting PHP Arrays to Class Properties Dynamically

A common pattern in legacy PHP code or dynamic data processing involves taking an associative array and injecting its key-value pairs directly into a class as properties. The goal is often to access these values naturally, like $this->username instead of $this->data['username']. While casting an array to (object) creates a stdClass instance that holds the data in properties, it fundamentally changes the type of the object. If your architecture requires strict typing or specific class inheritance, this cast may not align with your design goals.

To achieve true property injection while maintaining the original class structure, you need to explicitly define the variables within the constructor. The most direct approach involves iterating over the input array and assigning each value to a corresponding property using dynamic syntax. This ensures that $key becomes a native property of the instance rather than an element in a collection.

class MyClass {
    private $data;

    public function __construct(array $myarray) {
        // Dynamically create properties based on array keys
        foreach ($myarray as $key => $value) {
            $this->$key = $value;
        }
        
        // Optional: Store original data for introspection if needed
        $this->data = $myarray; 
    }
}

This foreach loop is not inefficient in the way one might assume. PHP's property assignment operator ($this->$key) handles the memory allocation and scope resolution efficiently. The overhead of creating multiple properties dynamically is negligible for typical application sizes, and it avoids the complexity of maintaining a massive array of static variable declarations at the top of the class file.

However, there are significant trade-offs to consider regarding validation and type safety. When you assign $this->$key = $value inside a loop, PHP does not enforce specific data types for those properties unless you use advanced features like property promotion with attributes (available in PHP 8+) or strict typing combined with reflection. If your array contains unexpected keys or values that break your business logic, the class will fail silently or behave unpredictably until runtime errors occur.

A more robust pattern involves defining a whitelist of expected properties or using Reflection to inspect and validate the input before assignment. This prevents pollution of the class namespace with irrelevant data. For example, if your class is designed to handle user data, you might only want id, name, and email to become properties, ignoring any extra keys present in the source array.

class MyClass {
    private $allowedKeys = ['name', 'age', 'city'];

    public function __construct(array $myarray) {
        foreach ($this->allowedKeys as $key) {
            if (isset($myarray[$key])) {
                $this->$key = $myarray[$key];
            }
        }
        
        // Handle unknown keys separately or ignore them
    }
}

In modern PHP development, specifically within the Laravel ecosystem, this manual injection is often unnecessary. Frameworks like Laravel provide robust data binding mechanisms that automatically map incoming arrays to model properties based on naming conventions or explicit mappings. If you are building an application where dynamic property creation is a core requirement, frameworks that offer flexible data casting or ORM features can simplify this process significantly. For instance, checking out resources from https://laravelcompany.com might provide insights into how to handle dynamic attributes within Laravel models without resorting to raw array manipulation.

Ultimately, the decision to use a foreach loop versus casting to stdClass depends on your architectural constraints. If you need a specific class type with defined behavior, dynamic property assignment is the correct path. It offers flexibility while keeping your object graph intact. Just remember that every dynamically created property bypasses static analysis tools and IDE intellisense unless properly documented or typed in PHP 8+, so always ensure your codebase remains testable and maintainable.

Our network