I got this PHP error of “Constant expression contains invalid operations”.

This is due to a function variable default value of new stdClass()
1 2 3 4 5 |
public function add(string $name, object $contents = new stdClass()){ /* function definition */ } |
This happens on PHP version 8.0.30 on my hosting server.

This errors doesn’t appear on my development laptop which is version 8.2.4.

Solution
I put “null” instead of “new stdClass()” and then set it to new stdClass if the variable is null.
1 2 3 4 5 |
public function add(string $name, object $contents = null){ if($contents == null): $contents = new stdClass(); endif; /* function definition */ } |