PHP constructor with a parameter

PHP constructor with a parameter

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

Stefan Bogdanescu

Founder & Senior Architect

PHP Constructor with a Parameter: Moving from Dynamic Properties to Structured Design

The core issue in your current code lies in how you are handling dynamic properties alongside object instantiation. Your existing __construct() method initializes every possible field (fvalue-string, fvalue-int, etc.) as empty or default values inside the class, then reassigns $this to that local $default variable. This is effectively discarding the instance's identity and creating a reference to an external object. Furthermore, you are manually setting properties like $f->{'fid'} outside the constructor logic.

You want to achieve this using a single call: new Field(1, 'fvalue-string', $_POST['data'], $arr). The parameters represent the unique ID, the property name, the data value, and the collection array. While PHP allows you to define constructors with arguments, passing a string key like 'fvalue-string' directly into the constructor does not automatically map that string to a specific class property without a mechanism to interpret it.

The Limitation of Standard Constructors

In standard PHP object-oriented programming, a constructor receives arguments that are mapped strictly by name or position to specific parameters defined in the function signature. If you define public function __construct($fid, $propName, $value, &$collection), you are not automatically creating a property named $propName inside the object unless your code explicitly handles it.

If you attempt to instantiate an object with dynamic keys based on string arguments passed to the constructor, you must decide how to store that data. Using stdClass is often the pragmatic solution when dealing with a schema-less or highly variable structure where property names are determined at runtime rather than compile time.

Here is how you can refactor your approach to accept parameters while maintaining type safety and clarity:

class MyRecord {
    public function __construct($fid, $propName, $value, &$collection) {
        // Create a new instance
        $record = new stdClass();
        
        // Set the unique identifier
        $record->fid = $fid;
        
        // Dynamically set the property based on the string name provided
        if (isset($propName)) {
            $record->$propName = $value;
        }
        
        // Add to the collection
        $collection[] = $record;
    }
}

// Usage
$arr = [];
$f1 = new MyRecord(1, 'fvalue-string', $_POST['data'], $arr);
$f2 = new MyRecord(2, 'fvalue-int', $_POST['data2'], $arr);

print_r($arr);

Why Use stdClass Here?

Your original code initializes a list of default properties (fvalue-image, fvalue-datetime, etc.) inside the constructor but then overwrites $this. This pattern suggests you were trying to create a generic container. In PHP, stdClass is the ideal candidate for this scenario. It allows you to add properties dynamically without needing to define them in the class definition or worry about type declarations on specific attributes until they are accessed.

By passing the property name as a string (e.g., 'fvalue-string') and the value as an argument, you decouple the data structure from the class definition. This flexibility is useful when building dynamic forms or handling API responses where the keys change based on input but follow a naming convention.

Trade-offs and Best Practices

While passing parameters to a constructor works well for initializing dynamic objects, it introduces a specific trade-off: lack of explicit schema. When you use new MyRecord(1, 'fvalue-string', ...), the resulting object has no type hints on its properties. This means you lose IDE autocomplete and static analysis capabilities for those specific fields unless you use reflection or interfaces later in the lifecycle.

If your application grows and requires strict typing (e.g., ensuring 'fvalue-int' is always an integer), relying solely on dynamic property assignment can lead to runtime errors that are difficult to trace. In such cases, defining a fixed set of properties in the class or using a DTO (Data Transfer Object) pattern becomes necessary.

Additionally, passing the collection array ($arr) into every constructor call is functional but couples the object creation tightly to the container management. In larger applications, you might prefer a factory method or a repository pattern that manages the $arr internally, preventing the need to pass it explicitly on every instantiation.

For complex dynamic structures where you need to enforce specific rules on how these objects are created, Laravel's JsonResource or Eloquent casts can offer more robust alternatives if you decide to integrate your data into a framework ecosystem like https://laravelcompany.com. However, for standalone scripts or lightweight MVC applications, the dynamic stdClass constructor approach remains a valid and efficient pattern for handling variable property sets.

Our network