PHP $this variable

PHP $this variable

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

Stefan Bogdanescu

Founder & Senior Architect

PHP $this Variable and Property Inference

When reviewing legacy code or third-party libraries, encountering a property access on $this without an explicit declaration in the class body can be jarring. Consider the following snippet:

class foo {
    function select($p1, $dbh = null) {
        if (is_null($dbh)) {
            $dbh = $this->dbh;
        }
        return; 
    }

    function get() {
        return $this->dbh;
    }
}

The immediate question is: where does $this->dbh come from? Is it a hidden local variable scoped to the select() method, or does it exist somewhere else? The answer lies in understanding how PHP handles properties and the scope of $this.

In this specific class definition, there is no declared property named $dbh within the body of class foo. However, because the code references $this->dbh, you are dealing with a dynamic property. PHP allows you to create properties on an object instance even if they were not declared in the class structure.

When the line $dbh = $this->dbh; executes inside the select() method, PHP implicitly creates a new property named dbh on that specific object instance. This value is stored in the internal hash table of the object ($object->__get($name) logic). It is not part of the class definition and will not appear if you inspect the static structure of foo, nor will it be available to other instances of foo unless they explicitly set it themselves.

This behavior contrasts with how modern frameworks or strict coding standards often handle data. In a statically typed language like TypeScript or C#, accessing an undeclared property results in a compile-time error. PHP's flexibility here allows for rapid prototyping but introduces significant risks regarding state management and debugging.

The Role of $this

The variable $this is automatically available within any non-static method of a class. It represents the current object instance upon which the method was called. When you write $this->dbh, you are telling PHP, "Look inside the memory allocation for this specific instance and find the property named dbh." If that property doesn't exist yet, PHP creates it on the fly.

This mechanism explains why the code works without a declaration. The property is instantiated dynamically at runtime. However, relying on dynamic properties can lead to subtle bugs. Since these properties are not part of the class definition, tools like IDEs cannot provide autocomplete suggestions or type hinting for them. You lose static analysis capabilities, making it harder to catch errors before they reach production.

Implications for State Management

If you were to instantiate two objects, new foo(), and call select() on one of them while passing a different database handle to the other, each object would maintain its own separate $dbh instance property.

$obj1 = new foo();
$obj2 = new foo();

// obj1 gets a dynamic $dbh property set here
$obj1->select('query', null); 

// obj2 never had select() called with null, so it has no $dbh property yet
// Attempting to return $this->dbh in get() would throw an Error: Undefined property: foo::$dbh

return $obj2->get(); // Fatal error!

The get() method assumes the property exists. If select() was never called with a null $dbh argument, or if another code path didn't trigger the dynamic assignment, accessing $this->dbh in get() will throw an Error: Undefined property. This violates the principle of encapsulation and makes the class fragile.

Modern Alternatives

In modern PHP development, particularly within ecosystems like Laravel, we generally avoid dynamic properties unless absolutely necessary for performance-critical legacy code or specific architectural patterns. Instead, we prefer explicit declarations:

class DatabaseConnection {
    private $dbh; // Explicitly declared

    public function setDbh($dbh) {
        $this->dbh = $dbh;
    }

    public function get() {
        return $this->dbh;
    }
}

By declaring $dbh as private, the property becomes part of the class contract. It is visible to static analyzers, IDEs can offer refactoring support, and the codebase remains self-documenting. If you need to share a database handle across methods, dependency injection is often the preferred approach rather than storing it as a dynamic instance variable.

For those looking to leverage modern PHP features or integrate this pattern into a larger application, resources like https://laravelcompany.com offer insights into structured approaches for managing database connections and service lifecycles without resorting to implicit state management.

Our network