PHP Classes and Objects — $this Error in Static Context
Fatal error: Using $this in static context causes 500 errors.
20+ years shipping production PHP systems at scale. Everything here is grounded in real deployments.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- Class is a blueprint; object is the cookie cut from it.
- Properties hold data; methods define behaviour — all inside the class.
- Constructor __construct() runs immediately on 'new' to set valid state.
- Use 'new ClassName()' to stamp out independent objects.
- Visibility (public, protected, private) controls who touches what.
- Assigning an object copies the reference, not the value — use clone for a true copy.
Think of a class like a cookie cutter and an object like the actual cookie. The cutter defines the shape — it's the blueprint. Every cookie you press out is a separate object made from that same blueprint. You can make a hundred cookies, each with different icing, but they all share the same shape because they came from the same cutter. In PHP, a class is that cutter, and every time you use 'new', you're pressing out a fresh cookie.
| Chrome | Firefox | Safari | Edge |
|---|---|---|---|
| ✓ | ✓ | ✓ | ✓ |
Every serious PHP application you've ever used — Laravel, WordPress, Symfony — is built on one foundational idea: objects. Not arrays. Not loose functions scattered across files. Objects. The reason experienced developers reach for OOP isn't because it sounds fancy; it's because real-world problems naturally map to things that have both data and behaviour. A user doesn't just have a name — a user can also log in, update their profile, and reset their password. Bundling that data and those actions together is exactly what classes let you do.
Before OOP, PHP code tended to sprawl. You'd have a users.php with fifty functions, half of them needing the same $db variable passed around, half of them accidentally sharing global state. Bugs were hard to trace because data lived everywhere. Classes solve this by giving each concept in your application its own fenced-off space — its own properties to hold data and its own methods to act on it. Change the internals of a class without breaking anything outside it. That's the deal.
By the end of this article you'll understand not just how to define a class and instantiate an object, but why the constructor exists, what visibility keywords actually protect, how to tell a class method from an instance method, and the patterns senior developers use daily. You'll also walk away knowing the mistakes that trip up 80% of beginners so you can skip straight past them.
What PHP Classes and Objects Actually Are
PHP classes are blueprints for objects — they define properties and methods that instances will hold. Objects are runtime instances of a class, each with its own memory space for property values. The core mechanic: a class declares structure; the new keyword materializes it into a live object.
When you call a method on an object, PHP automatically injects $this as a reference to that specific instance. This is how methods access an object's own properties and other methods. Static methods, declared with the static keyword, belong to the class itself, not any instance — they cannot use $this because there is no object context. Calling a non-static method statically (e.g., ClassName::method()) triggers a deprecation warning in PHP 7 and an error in PHP 8, because $this is undefined.
Use classes and objects when you need to model entities with state and behavior — users, orders, HTTP requests. In real systems, this is the foundation for encapsulation, dependency injection, and testable code. Without objects, you end up with global state and procedural spaghetti that breaks under any non-trivial load.
Defining a Class: Blueprint Before You Build Anything
A class is a template. It describes what a thing looks like (its properties) and what a thing can do (its methods). Nothing actually exists in memory until you instantiate it with 'new'. This is the most important mental model shift: writing a class doesn't create a user, it defines what a user is.
Properties are variables that belong to the class. Methods are functions that belong to the class. Both live inside the class body, and both can be marked as public, protected, or private — more on that shortly.
The constructor is a special method named . PHP calls it automatically the moment you use 'new __construct()ClassName()'. Its job is to set the object up in a valid state. If you're building a BankAccount, the constructor should insist on an opening balance. You shouldn't be able to create a BankAccount that starts in an undefined, broken state — the constructor is your gatekeeper.
Notice in the example below how $this refers to the specific object being worked with. It's the object saying 'my own property'. Every object has its own copy of properties, which is why two BankAccount objects can have different balances without interfering with each other.
deposit(), withdraw(), and transfer() method separately.__construct()Visibility Keywords: public, protected, and private Actually Enforced
Visibility is the mechanism that lets you separate what an object exposes to the world from what it keeps to itself. Most beginners mark everything public because it's easier. That's a trap — it means any code anywhere in your codebase can reach in and mangle your object's state without going through your methods.
Think of it like a car dashboard. The steering wheel and pedals are public — they're designed to be used by the driver. The engine internals are private — you're not meant to reach in and adjust the fuel injectors directly while driving. That encapsulation is what makes the car safe to use.
public means anyone, anywhere can access it. protected means only this class and any class that extends it can access it (useful for inheritance). private means only code inside this exact class can access it.
The real-world pattern most PHP developers use: make all properties private, then expose only what outside code genuinely needs through carefully designed public methods. This is called encapsulation and it's one of OOP's four pillars. The payoff is that you can completely rewrite how a class stores its data internally without breaking any code that uses the class — as long as the public methods keep working the same way.
Static Methods and Properties: When the Class Itself Needs to Know Things
Every object you've seen so far has its own independent copy of its properties. That's usually what you want. But sometimes a piece of data or behaviour belongs to the class itself — not to any one instance of it. That's what static is for.
A classic example is a counter tracking how many objects of a class have been created. You can't store that on any single object because no single object knows about the others. The class needs to hold it centrally.
Another common use case is factory methods — static methods that construct and return a new instance with a specific configuration. Laravel and many modern PHP frameworks use this pattern heavily: User::create([...]), Carbon::now(), Response::json(...).
Access static members with the :: operator (called the scope resolution operator), not ->. Inside the class, use self:: to refer to the class itself rather than $this. Using $this inside a static method is a fatal error because there is no 'this' — no object is involved.
Use static sparingly. Overusing it leads you back toward procedural code with global state. The sweet spot is factory methods and genuine class-level metadata like the counter below.
Object Cloning and Comparison: Two Gotchas That Bite in Production
Objects in PHP are passed by reference-like handles. This trips up developers who come from a JavaScript or Python background and also those who've only worked with PHP primitives. When you assign an object to a new variable, you don't get a copy — both variables point at the same object. Change it through one variable and the other sees the change too.
To get a true independent copy, you use the clone keyword. PHP then calls the magic method on the new copy if you've defined one — use that to deep-clone any nested objects the class holds, because clone is shallow by default.__clone()
Comparison has its own wrinkle. == checks if two objects have the same class and same property values. === checks if both variables point to the exact same instance in memory. This matters in tests and in any logic where identity (not just equality) matters.
This section pulls together everything from the article — you'll see a class with a constructor, private properties, a public API, and now cloning all working together. Think of this as the capstone example.
__clone(), cloning gives you a new outer object but the nested objects are still shared. Mutate a nested object on the clone and you've mutated the original too. Always implement __clone() when your class contains object properties.debug_zval_refs() on suspected objects to see reference counts. If you see refcount > 1 and no intentional sharing, you've got a shallow clone problem.__clone() to deep-copy them.__clone() is your deep-copy hook.__clone() and deep-copy each object property__clone(), manually reassign those properties to the same referenceInheritance in PHP: Extending Classes and Method Overriding
Inheritance lets you create a new class based on an existing one. The child class (subclass) inherits all public and protected properties and methods from the parent class (superclass). You can then add new properties and methods, or override existing ones to change behaviour.
PHP supports single inheritance — a class can extend only one parent class. But a parent class can have many children. This is the classic 'is-a' relationship: a Truck is a Vehicle, a Circle is a Shape.
The child class uses the extends keyword. Inside the child, you call parent::method() to invoke the parent's version of a method. Overriding methods must have compatible signatures — PHP enforces this at compile time.
A common mistake is forgetting to call the parent constructor if the parent has mandatory setup logic. A child class must explicitly call parent:: if the parent's constructor is defined and does important work.__construct()
Use inheritance when the child class genuinely is a more specific version of the parent. If the relationship is more about sharing behaviour than identity, favour composition or traits instead.
- A child class must be a specialised version of the parent (Dog extends Animal).
- If you're thinking 'this new class needs the same methods as that class', consider composition: pass the behaviour in via dependency injection.
- PHP's single inheritance means you get only one shot at the parent. Choose wisely.
- Favour composition over inheritance — it's less brittle and easier to test.
__construct() if the parent has one.Interfaces: The Contract That Saves Your Weekend
Here's a truth that hits hard after a 3AM rollback: production doesn't care about your intents, only your contracts. PHP interfaces enforce a specific set of required methods across unrelated classes. No ambiguity, no "well, we thought it worked."
Why this matters: You define an interface when multiple classes must implement the same behavior, but they implement it differently. Your payment gateway, for example, might have a PayPalStrategy and a StripeStrategy. Both must implement charge(float $amount) and refund(string $transactionId). The interface ensures that when your boss says "add a new processor," you literally cannot forget those methods.
The contract is enforced at compile-time. If a class says implements PaymentGateway but doesn't define charge(), PHP throws a fatal error before your code reaches staging. Not a warning. Not a log. A hard stop.
Inheritance is about sharing implementation. Interfaces are about sharing capability. Use them when you need to guarantee behavior without dictating how it's done.
Abstract Classes: When You Want Partial Answers
An abstract class is the middle ground between a concrete class and an interface. It contains some implemented methods and some placeholders (abstract methods) that child classes must fill. Think of it as a partially-written blueprint with critical gaps your team must complete.
Why reach for this? When you have shared logic across related classes but need to force specific implementations for certain behaviors. Your DataExporter base class might have the export() method fully written, but it requires getData() and formatFile() to be defined by each subclass (CSV, PDF, JSON). The abstract class handles the boilerplate; the subclass handles the unique parts.
In PHP 8.x, abstract classes can have typed properties, named arguments, and full constructor promotion. They're not legacy—they're tactical.
Important: You cannot instantiate an abstract class directly. If someone writes $exporter = new DataExporter(), PHP will throw a fatal error. That's the feature, not a bug. You're forcing your team to think about specialization before execution.
Traits: Reuse Without Inheritance Hell
PHP single-inheritance model means a class can only extend one parent. That's a hard limit—your ReportGenerator can't extend both PdfRenderer and EmailSender. Traits are the escape hatch: they let you compose behavior into a class without constructing a fragile inheritance pyramid.
Think of a trait as a copy-paste that PHP manages for you. When a class uses a trait, PHP copies the trait's methods directly into the class at compile-time. No diamond problem, no fragile base class syndrome. Just reusable code that lives in its own file.
In PHP 8.x, traits support abstract methods, properties, and even other traits. Use them for cross-cutting concerns like logging, timestamp management, or caching logic that multiple unrelated classes need.
Watch the recall trap: If two traits define the same method, PHP throws a fatal error unless you resolve the conflict with insteadof or as. You'll discover this immediately in CI, not in production.
Readonly Classes (PHP 8.2) for Immutable DTOs
PHP 8.2 introduced readonly classes, a powerful feature for creating immutable data transfer objects (DTOs). When a class is declared readonly, all its properties are automatically readonly, meaning they can only be initialized once (typically via constructor promotion) and cannot be modified afterward. This eliminates the need to manually mark each property as readonly and ensures the entire object is immutable.
Example: ```php readonly class UserDTO { public function __construct( public string $name, public string $email, ) {} }
$user = new UserDTO('Alice', 'alice@example.com'); // $user->name = 'Bob'; // Error: Cannot modify readonly property ```
Readonly classes are ideal for DTOs, value objects, and configuration objects where immutability is desired. They also support inheritance: a readonly class can extend another readonly class, but not a non-readonly class. Additionally, readonly classes can implement interfaces and use traits.
However, there are limitations: readonly classes cannot have static properties, and property hooks (PHP 8.4) are not allowed on readonly properties. Also, if you need lazy initialization or computed properties, a readonly class may not be suitable.
In production, readonly classes help prevent accidental mutation of data, making code more predictable and easier to debug. They are particularly useful in event sourcing, CQRS, and API response objects.
New in Initializers (PHP 8.1) for Cleaner Constructor Defaults
PHP 8.1 introduced "new in initializers," allowing you to use the new keyword directly in default parameter values, property declarations, and attribute arguments. This simplifies code by removing the need for constructors or helper methods to instantiate default objects.
Example without new in initializers: ``php class Logger { private Formatter $formatter; public function __construct(Formatter $formatter = null) { $this->formatter = $formatter ?? new ``JsonFormatter(); } }
With new in initializers: ``php class Logger { public function __construct( private Formatter $formatter = new ``JsonFormatter(), ) {} }
- Default parameter values (as shown)
- Default property values (for promoted properties)
- Attribute arguments (e.g.,
#[Route(new)DefaultController())]
It is particularly useful for dependency injection defaults, test doubles, and configuration objects. However, be cautious: the expression is evaluated only once at the point of definition, not each time the default is used. For objects that need fresh instances, use a factory or a named constructor.
In production, new in initializers reduces boilerplate and makes constructor signatures cleaner. It's especially beneficial in large codebases where many classes have optional dependencies with sensible defaults.
new in default parameters, reducing constructor boilerplate.Property Hooks (PHP 8.4) for Getter/Setter Logic
PHP 8.4 introduced property hooks, allowing you to define getter and setter logic directly on properties without writing separate methods. This brings a more elegant syntax for computed properties, validation, and lazy loading.
Example: ```php class User { public string $name { set => ucfirst(strtolower($value)); get => $this->name ?? 'Guest'; } }
$user = new User(); $user->name = 'aLiCe'; echo $user->name; // Alice ```
Property hooks are defined using curly braces after the property declaration. The get hook runs when the property is read, and the set hook runs when a value is assigned. The set hook receives $value (the assigned value) and must return the value to store (or throw an exception). The get hook returns the computed value.
Hooks can access the property's backing value via $this->propertyName, but be careful to avoid infinite recursion. They work with typed properties, promoted properties, and even readonly properties (though readonly properties only allow get hooks).
Property hooks are a game-changer for reducing boilerplate getter/setter methods. They are especially useful for: - Normalization (e.g., trimming strings) - Validation (e.g., throwing on invalid values) - Lazy loading (e.g., fetching from database on first access) - Computed properties (e.g., full name from first and last)
In production, property hooks make code more readable and maintainable by keeping logic close to the property declaration. However, avoid complex side effects in hooks to keep them predictable.
Fatal Error: Using $this in Static Context Took Down a Deployment
- Never use $this inside a static method — PHP will kill the request.
- When you see static, you should not see $this anywhere in that method chain.
- Add static analysis to your CI pipeline to catch this before it hits production.
User() before calling methods). Review constructor logic — any condition that might skip assignment?__clone() method that deep-clones each nested object. Use debug_zval_refs() to check reference counts before and after clone.var_dump($object->properties) // See all current valuesprint_r(get_object_vars($object)) // List all accessible properties| File | Command / Code | Purpose |
|---|---|---|
| BankAccount.php | class BankAccount | Defining a Class |
| UserProfile.php | class UserProfile | Visibility Keywords |
| DatabaseConnection.php | class DatabaseConnection | Static Methods and Properties |
| ShoppingCart.php | class CartItem | Object Cloning and Comparison |
| VehicleInheritance.php | abstract class Vehicle | Inheritance in PHP |
| PaymentGatewayInterface.php | interface PaymentGateway | Interfaces |
| DataExporter.php | abstract class DataExporter | Abstract Classes |
| LoggerTrait.php | trait LoggerTrait | Traits |
| readonly_dto.php | readonly class UserDTO { | Readonly Classes (PHP 8.2) for Immutable DTOs |
| new_in_initializer.php | class JsonFormatter { | New in Initializers (PHP 8.1) for Cleaner Constructor Defaul |
| property_hooks.php | class User { | Property Hooks (PHP 8.4) for Getter/Setter Logic |
Key takeaways
__clone() when the class holds nested objects.__construct(). Keep hierarchies shallowInterview Questions on This Topic
What is the difference between a class and an object in PHP, and can you give a real-world analogy to illustrate it?
Frequently Asked Questions
20+ years shipping production PHP systems at scale. Everything here is grounded in real deployments.
That's OOP in PHP. Mark it forged?
9 min read · try the examples if you haven't