When should I declare variables in a PHP class?

When should I declare variables in a PHP class?

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

Stefan Bogdanescu

Founder & Senior Architect

When should I declare variables in a PHP class?

In modern PHP, the distinction between declared and undeclared class properties has shifted significantly from how it worked in older versions of the language. If you are coming from legacy PHP 4 or early PHP 5 codebases, the behavior described in your example—where $undeclaredVar works just as well as a declared property—might seem like a feature rather than a quirk. However, relying on this dynamic creation of properties creates ambiguity that can lead to subtle bugs and performance overhead.

Dynamic Property Creation vs. Type Safety

In the code snippet you provided, PHP dynamically creates the $undeclaredVar property when it encounters the assignment $this->undeclaredVar = "I wasn't declared...". Because no visibility modifier (like public, protected, or private) was attached to this dynamic creation, PHP defaults it to public. This is why you can access and modify $undeclaredVar from outside the class instance just like $declaredVar.

This behavior stems from PHP's loose typing. The language does not enforce that a property must be defined in the class body before it is assigned to. While this flexibility allows for quick prototyping, it removes compile-time (or rather, parse-time) checks. If you accidentally misspell a property name, say $this->declaredVar as $this->declaredVra, PHP will not throw an error in a non-strict environment; it will simply create a new property named declaredVra. In a strict type-checking environment or when using attributes like #[\Override], this behavior is often flagged as suspicious.

The Shift to Strict Standards

The most compelling reason to declare variables up front is the ability to enforce visibility and types. When you define a property at the class level:

class TestClass
{
    public string $declaredVar;
}

You are explicitly stating that this data belongs to the object and defining its scope. You can then immediately set it in the constructor or via dependency injection, ensuring the invariant holds true before any logic runs.

If you omit the declaration:

class TestClass
{
    function __construct()
    {
        $this->declaredVar = "Hello"; // Creates a public property dynamically
    }
}

You have lost control over the initial state and visibility. While PHP allows this, tools like PHPStan or Psalm will often report these as "properties not declared in class," indicating a deviation from best practices. This is particularly relevant when migrating to strict error reporting (declare(strict_types=1);), which can cause fatal errors if you try to access an undeclared property without first defining it, depending on the specific context and version.

Static Analysis and Refactoring

Declaring properties upfront enables static analysis tools to understand your codebase accurately. If you have a property $undeclaredVar, a developer reading the code might assume it doesn't exist until they run the script. Conversely, if it is declared as private string $undeclaredVar;, any attempt to access it from outside the class will result in a clear error, preventing unintended side effects.

Furthermore, refactoring becomes safer when properties are known entities. Tools can automatically rename or migrate properties across a codebase only if they are statically defined. Dynamic properties introduce "ghost" members that analysis tools cannot track reliably, increasing technical debt.

The Laravel Ecosystem Context

If you are working within the Laravel framework, this distinction is even more critical. Laravel relies heavily on type hints and strict standards to ensure robustness, especially when using features like Dependency Injection or Service Containers. When binding a class into the container, passing undeclared properties can lead to confusing hydration issues where data is expected but not formally defined in the contract of the class.

For instance, using attributes in newer PHP versions (8.0+) allows you to define default values and visibility declaratively:

class User
{
    #[\Attributes\DefaultValue('active')]
    public bool $isActivated = false;
}

Attempting to rely on dynamic creation bypasses these modern features entirely. As noted in best practices for maintaining scalable applications, explicit is better than implicit. Resources like LaravelCompany often emphasize the importance of adhering to strict typing standards to prevent runtime surprises in production environments.

Best Practice Recommendation

Always declare your properties at the top of the class with their intended visibility and type hint. This practice ensures that your code is self-documenting, analyzable by modern tools, and resistant to the silent failures that dynamic property creation invites.

Our network