Getting the name of a child class in the parent class (static context)

Getting the name of a child class in the parent class (static context)

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

Stefan Bogdanescu

Founder & Senior Architect

The Limits of get_class() in Static Contexts

Attempting to retrieve the name of a child class from within its parent using static methods is a classic trap for developers building generic frameworks or ORM libraries. The scenario you encountered highlights a fundamental asymmetry in how PHP handles reflection and namespaces: dynamic resolution works perfectly inside instance methods, but static contexts strip away the context required to identify the specific subclass being called.

In your example, calls like get_class(parent), get_class(self), and even the bare get_class() all resolve to BaseModel or return false when executed statically via User::get(). This is not a bug; it is by design. When you invoke User::get(3), PHP resolves the method name against the User class, but inside the static method body, there is no "this" object yet, nor is there an active inheritance chain that self can reference back to the caller. The static method exists in a vacuum regarding its specific child implementation until that method is instantiated or passed a specific instance context.

Why Static Resolution Fails

The core issue lies in how self and static behave without an object context. In a non-static function, get_class(self) looks at the class of the current object. However, inside a static method called on a child class, there is no $this. Consequently, self resolves to the class where the method was defined (BaseModel), and __CLASS__ hard-codes that same definition location.

There is no native language construct in PHP 5 or 7 that allows a static method to "look up" the calling class name dynamically without passing it explicitly. This is why your attempts to use get_class(parent) failed; parent refers to the parent of the current scope's class, but since the scope is static and defined in BaseModel, the parent relationship doesn't magically extend to the caller.

The Reflection Solution

To solve this in a generic ORM pattern where you need to instantiate the correct child class based on the method call, you must rely on Reflection API rather than internal variables. While PHP 8 introduced true late static binding for many properties and methods, older versions (and specific static contexts) require explicit reflection to bridge the gap.

You can retrieve the actual called class name by inspecting the calling scope within the function itself, but standard get_class() won't work directly. Instead, you often have to accept that the static method must be passed an instance or rely on a different architectural pattern. However, if your goal is strictly to know which class invoked the static method, you can use debug_backtrace().

Here is how you can implement a workaround that identifies the caller:

class BaseModel {
    /**
     * Return an instance of a Model from the database.
     */
    public static function get($id) {
        // Get the backtrace to find who called us
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        
        // The first frame is usually inside this function (or the call stack entry)
        // The second frame is typically the caller's class in a static context
        if (isset($trace[1])) {
            $callerClass = $trace[1]['class'] ?? null;
            
            // If debug_backtrace returns null for class, it might be called from CLI or global scope
            if ($callerClass === false || $callerClass === 'BaseModel') {
                throw new \InvalidArgumentException('get() must be called on a specific model class.');
            }

            // Now you have the actual child class name
            $class = $callerClass;
        } else {
             // Fallback if backtrace is insufficient (e.g., global scope call)
            $class = __CLASS__;
        }

        // Query the database with id
        $row = self::get_row_from_db($id);

        // Return the filled instance
        $obj = new $class();
        $obj->data = $row;
        
        return $obj;
    }

    private static function get_row_from_db($id) {
        // Mock implementation
        return ['id' => $id, 'name' => 'Unknown'];
    }
}

Architectural Trade-offs

Relying on debug_backtrace() introduces a slight performance overhead due to stack inspection and potential security implications if the backtrace data is logged or exposed. A more robust approach for an ORM is to avoid static factory methods that attempt to guess the class type entirely.

Instead, consider passing the model class explicitly as a dependency or utilizing a service locator pattern where the framework knows about all models upfront. Alternatively, you can leverage PHP 8's static keyword behavior if your base class uses it for method resolution, though this only works if the method is defined in the child class or if late static binding is strictly enforced for properties.

If you are building a library intended to be reusable across different projects, hard-coding assumptions about how classes will call each other can lead to tight coupling. The debug_backtrace() approach provides the flexibility you need but requires careful error handling to ensure it isn't called from an unexpected context.

For many developers working with Laravel or similar frameworks, this specific limitation is why dependency injection and repository patterns are preferred over monolithic static factories. If you find yourself needing this specific dynamic resolution feature frequently, exploring how ReflectionClass interacts with get_called_class() (which only works inside non-static methods) might be the next logical step in your design evolution.

Ultimately, the solution isn't a magic function that reveals the caller in a static context without assistance; it is an architectural decision to either pass the class name explicitly or refactor the method to accept an instance where get_class() becomes trivial again.

Our network