PHP Reference ยท Functions and Classes
new in initializers (PHP 8.1)
Reference for PHP 8.1 new in initializers: use new as a parameter default, in static variables and global constants, with limits and examples.
Before PHP 8.1, a default value had to be a constant expression such as a number, string or array. Since 8.1 you can write new ClassName(...) as the default of a parameter, so a function can fall back to a ready-made object when the caller passes none.
This removes the old ?Logger $logger = null followed by $logger ??= new NullLogger() boilerplate and makes the default visible in the signature.
function process(Logger $logger = new NullLogger()): void { /* ... */ }
Try it
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.
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.
Where it is allowed
| Place | Allowed |
|---|---|
| Parameter defaults (functions, methods, closures) | Yes |
| Constructor-promoted parameters | Yes |
static variable initializers |
Yes |
Global constants declared with const |
Yes |
| Attribute arguments | Yes |
| Class property defaults | No |
| Class constants | No |
Using new in a place that is not allowed is a compile-time error: "New expressions are not supported in this context".
Usage notes
- Evaluated on each call. The default expression runs every time the argument is omitted, so each call gets its own fresh object, as the first line of the second example shows (
111). - Arguments must be constant expressions themselves: literals, constants, other
newexpressions and array literals. You cannot pass variables or function calls. - Dynamic class names, anonymous classes and spread (
new $class,new class {},new Foo(...$args)) are not allowed in initializers. - Static variables and global constants receive the object once, when first evaluated, so state is shared afterwards.
- Enums are often simpler. For a fixed set of choices, an enum case as default (
Level $level = Level::Low) needs nonew. - Why not property defaults? Property defaults are evaluated once at class level, which would share a single object between all instances; assign objects in the constructor instead.
- Readonly pitfall. A readonly promoted property with a
newdefault is fine; the object is created per call.