Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 147 ยท Object-Oriented PHP

Constructors and Destructors

Initialize PHP objects with __construct, constructor property promotion, named arguments, new in initializers, __destruct and new without parentheses.

In the previous lessons you created objects with new and then set their properties one by one. That's fragile: nothing forces the caller to set every property, so an object can exist in a half-built state, with an empty name or an uninitialized email. A constructor fixes this. It's a special method that PHP runs automatically every time an object is created, and it receives the values the object needs to be valid from the very start.

This lesson covers __construct(), the PHP 8.0 shortcut called constructor property promotion, default values and named arguments, new in initializers (PHP 8.1), the opposite end of an object's life with __destruct(), and the PHP 8.4 syntax that lets you call methods on new Something() without extra parentheses.

__construct()

A constructor is a method named __construct (two underscores). PHP calls it right after creating the object, passing it the arguments you wrote after the class name in new:

PHP A first constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Now a Book can't exist without a title, author and page count. Forgetting an argument throws an ArgumentCountError before any object is returned, and passing the wrong type throws a TypeError, exactly like a normal function call.

Some rules about constructors:

  • A constructor has no return type and doesn't return a value. new always gives you the object.
  • Its name is always __construct. PHP 4 used a method named after the class; that style stopped working as a constructor in PHP 8.0.
  • A class without a constructor is fine: new Thing() just creates the object with property defaults.
  • It's normally public. A private constructor stops outside code from using new, which is how named constructors and static factories force callers through a specific method.

Validating in the constructor

A constructor is the ideal place to check the arguments. If the values are invalid, throw an exception. The new expression then fails and no half-valid object ever reaches the caller:

PHP Rejecting invalid objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Once a function receives an EmailAddress, it knows the address is normalized and valid; it doesn't have to check again. Small classes like this, which wrap one value and guarantee its rules, are called value objects, and you'll build more of them in Readonly Properties and Immutable Objects. Using filter_var() for validation is covered in Form Validation.

Constructor property promotion (PHP 8.0)

Look back at the Book class: each property's name and type appears three times (the property declaration, the parameter and the assignment). PHP 8.0 added constructor property promotion to remove that repetition. Put a visibility keyword in front of a constructor parameter and PHP declares the property and assigns it for you:

PHP Promoted properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

That class is exactly equivalent to the first Book, with a third of the code. The var_dump() shows three ordinary private properties. Promoted constructors are the standard style in modern PHP, and the formatting above (one parameter per line, trailing comma, empty body { } on separate lines) is the common convention.

Things to know about promotion:

  • Any visibility works (public, protected, private), and so do readonly (see readonly properties) and PHP 8.4's asymmetric visibility such as public private(set).
  • You can mix promoted and normal parameters. A normal parameter is just a local variable inside the constructor.
  • The constructor body still runs, after promoted properties have been assigned, so you can validate or compute other properties there.
  • A promoted parameter can't be variadic (private string ...$tags is not allowed) and can't have the type callable.
  • A property can't be both declared in the class body and promoted.

Here's a constructor that uses all of this together:

PHP Mixing promoted and normal parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Default values and named arguments

Constructor parameters can have default values like any function. Combined with named arguments (PHP 8.0), this makes objects with several options readable at the call site:

PHP Defaults and named arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is HTML source text; on a web server, the browser would render these as buttons. With named arguments, you can skip $color and $size and set only disabled, and you can pass arguments in any order. The label is escaped with htmlspecialchars() (note & in the last line) because every HTML-producing example must escape its data, as explained in Preventing XSS.

Notice new Button('Save')->render(). That syntax is new in PHP 8.4, and it gets its own section below.

Named arguments make parameter names part of your public API. Once callers write new Button(disabled: true), renaming $disabled breaks their code. Choose constructor parameter names carefully.

new in initializers (PHP 8.1)

Parameter defaults must normally be constant values. PHP 8.1 made one exception: a default can be a new expression. That's ideal for optional dependencies, where the caller can pass a real object but a sensible one is created otherwise:

PHP A default object as a parameter default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The default object is created fresh for each call that doesn't pass one, not shared between objects. Passing the clock in from outside instead of creating it inside the class is called dependency injection; it's what makes Greeter testable with a fixed time. The interface keyword is explained in Abstract Classes and Interfaces, and OOP Design Principles explains why this design matters.

new in initializers is allowed in parameter defaults, static variable initializers, global constants and attribute arguments. It is not allowed in property defaults or class constants: private Clock $clock = new SystemClock(); is a compile error ("New expressions are not supported in this context"). Promotion, as above, is the way to get the same effect.

__destruct()

The opposite of a constructor is a destructor, a method named __destruct() that PHP calls when an object is about to be destroyed. PHP destroys an object as soon as nothing refers to it anymore: the last variable holding it is reassigned or unset, or a function's local variable goes out of scope. Any objects still alive when the script ends are destroyed then.

PHP When destructors run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output carefully. In step 2, B2 is created before B1 is destroyed, because the new object must exist before it's assigned. In step 3, unsetting $c does nothing visible, since $alias still holds the object. B2 is destroyed only after "5. end of script", when PHP cleans up the remaining objects.

Destructors have a few sharp edges:

  • If a constructor throws, the object is never fully created and its destructor doesn't run.
  • Objects that reference each other in a cycle (A holds B, B holds A) aren't destroyed when your variables go away. PHP's cycle collector frees them later, at a moment you don't control.
  • Destructors run after exit(), but not after a fatal error, so they're not a reliable place for critical work.
  • Throwing an exception from a destructor during script shutdown leads to a fatal error.

In practice, you'll rarely write a destructor. PHP closes files, database connections and other resources automatically when the objects that own them disappear. Use one only when an object must release something PHP doesn't know about, such as deleting a temporary file it created, and prefer explicit methods like close() for anything important.

new without parentheses (PHP 8.4)

Before PHP 8.4, calling a method directly on a new object needed an extra pair of parentheses around the new expression:

PHP
echo (new Button('Save'))->render();       // works in all PHP versions

PHP 8.4 removed that requirement. You can access methods, properties, constants and static members directly on new ClassName(...):

PHP Chaining on new (PHP 8.4)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

One rule: the class name must be followed by an argument list, even an empty one. new Temperature()->fahrenheit() works, but new Temperature->fahrenheit() is a parse error, because without () PHP can't tell where the class name ends. If your code must also run on PHP 8.3 or older, keep the wrapping parentheses.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does public function __construct(private int $qty = 1) {} do?

    That's constructor property promotion (PHP 8.0). The visibility keyword turns the parameter into a property that is assigned automatically.
  2. 2. A constructor throws an exception because an argument is invalid. What does the caller get?

    The new expression itself fails. If the exception isn't caught, the script stops; either way no object reaches the caller.
  3. 3. In this code, when is "B1 destroyed" printed? $b = new Tracker("B1"); $b = new Tracker("B2");

    The new object is created first, then assigned to $b. At that moment B1 has no references left and PHP destroys it immediately.
  4. 4. Which line is valid in PHP 8.4?

    PHP 8.4 allows member access on new without wrapping parentheses, but only when the class name has an argument list. New expressions still can't be property defaults.
  5. 5. Why might a constructor parameter default to new NullLogger()?

    New in initializers (PHP 8.1) creates the default object for each call that omits the argument, which keeps dependency injection optional.

Summary

  • __construct() runs automatically on new and receives its arguments. Use it to require and validate everything an object needs; throw an exception to reject invalid input.
  • Constructors have no return type. A class without one is fine; a private constructor blocks new from outside.
  • Constructor property promotion (PHP 8.0): a visibility keyword on a parameter declares and assigns the property. It works with readonly, defaults and normal parameters, but not variadics or callable.
  • Defaults plus named arguments make option-heavy constructors readable: new Button('Save', disabled: true).
  • new in initializers (PHP 8.1) lets a parameter default be an object, Clock $clock = new SystemClock(); not allowed in property defaults or constants.
  • __destruct() runs when the last reference to an object disappears, or at script end. You'll rarely need one.
  • PHP 8.4 allows new Temperature(25)->fahrenheit() without wrapping parentheses; the () after the class name is required.

Next: Inheritance