php create object without class

php create object without class

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

Stefan Bogdanescu

Founder & Senior Architect

PHP Create Object Without Class

In JavaScript, creating an anonymous object is a trivial operation involving simple bracket notation. You define the properties inline, and the runtime handles the rest. For example:

myObj = {};
myObj.abc = "aaaa";

PHP offers a similar capability, but the syntax has evolved significantly since the early days of the language. A common legacy pattern found in older tutorials involves casting an associative array to an object using the (object) cast operator:

$obj = (object) array('foo' => 'bar', 'property' => 'value');

This technique works in PHP 5 and remains valid in modern versions, yet it forces you to construct an array first before casting it. If your goal is to create an object without explicitly defining a class, you might wonder if there is a cleaner alternative available since PHP 5.4. The short answer is that the core language syntax for this specific task hasn't changed fundamentally; however, modern best practices have shifted away from manual casting in favor of type declarations and constructor functions.

The legacy (object) cast is functionally equivalent to defining an object with properties initialized directly. It creates a stdClass instance (unless a custom class is targeted) and populates its public properties immediately. While this works, it lacks the explicitness that modern PHP enforces. In recent versions, the language encourages declaring the type of variables you are creating. If you need to create an object without a named class definition in your current scope, casting an array remains one of the few ways to achieve dynamic property initialization on a generic object.

However, there is a more robust approach when dealing with structured data that needs to behave like an object: using stdClass or creating a dedicated anonymous function that returns an object. If you are working in a modern PHP environment (8.x), you can leverage type hints to ensure the structure remains consistent even if no named class exists.

Consider a scenario where you need to pass configuration data as an object to a method expecting an array or specific properties. Using the cast is quick, but it creates a stdClass by default. If you require private properties or methods later, this approach fails because stdClass only allows public properties by design. In those cases, defining a class—even one that exists solely for that purpose—is often the superior solution.

$config = (object) [
    'timeout' => 30,
    'retries' => 3,
];

// Accessing properties works as expected
echo $config->timeout; // Output: 30

If you strictly require an object without any class definition and need to add methods later, the legacy cast becomes limiting. The modern alternative is to use a factory function or a closure that returns a stdClass instance. This pattern decouples the creation logic from the runtime state while maintaining the "no class" constraint you requested.

function createConfig(array $data): stdClass {
    return (object) $data;
}

$config = createConfig(['key' => 'value']);

This approach ensures type safety through return type declarations, a feature introduced in PHP 7 and refined in PHP 8. It also allows for validation before the object is created, something you cannot do with a direct cast. The trade-off here is slightly more verbose syntax compared to the one-liner cast, but it gains significant clarity regarding intent.

Another consideration is serialization. Objects created via (object) array casting serialize correctly using json_encode, provided all properties are public and compatible with JSON types. If you attempt to access a property that was not passed in the initial array, PHP will throw a notice if strict mode is enabled or simply return null depending on how the object was instantiated.

While some might argue for using the JsonSerializable interface to create complex structures, doing so without a class definition is impractical because you must extend an existing class or define one to implement that interface. Therefore, sticking to the cast operator for simple, flyweight objects remains valid, but wrapping it in a typed function is the recommended practice for production codebases to avoid accidental property mutations and ensure consistency.

Our network