new expression is used to create an instance of a class. But it was not allowed to be used as parameter default values. So up until now we had to do something like this:
function execute($query, $connection = null) {
$connection ??= new DefaultConnection(); // DefaultConnection will be used if no $connection passed
// now execute the query
}
But, problem with this is, it's not possible to know what is the actual default value for $connection by reading function signature only. We have to read the full function body to know it. Also, it is bit more verbose.
So to make things better, PHP 8.1 now supports usage of new expressions inside parameter default values, attribute arguments, static variable initializers and global constant initializers.
So we can now accept default parameter value like this:
function execute($query, $connection = new DefaultConnection()) {
// do something
}
execute('some query');
// as we didn't pass any $connection, DefaultConnection will be used
Also, we can use objects as variable static & global constants.
global $connection = new DefaultConnection(); // please don't use global variable ever
const DEFAULT_CONNECTION = new DefaultConnection();
define('DEFAULT_CONNECTION', new DefaultConnection()); // we can now use object in define() too
Note:
Write comment about this article: