Skip to content

Instantly share code, notes, and snippets.

@coogle
Created August 27, 2024 03:48
Show Gist options
  • Save coogle/7c0fbb750288ebdd1feb8a5e9185ba8c to your computer and use it in GitHub Desktop.
Save coogle/7c0fbb750288ebdd1feb8a5e9185ba8c to your computer and use it in GitHub Desktop.
Why I think default expressions for default parameters are not a good idea.
<?php
enum LoggerType: string
{
case DB = 'db';
case FILE = 'file';
case CLOUD = 'cloud';
public function getLogger(): LoggerInterface
{
return match($this)
{
static::DB => new DatabaseLogger(),
static::FILE => new FileLogger(),
static::CLOUD => new CloudLogger()
};
}
}
interface LoggerInterface
{
public function log(string $x): LoggerInterface;
}
// Assume DatabaseLogger, etc. exist and implement LoggerInterface
class A
{
protected ?LoggerInterface $log;
public function withLogger(LoggerInterface|LoggerType $a = new DatabaseLogger): static
{
if($a instanceof LoggerInterface)
{
$this->log = $a;
return $this;
}
$this->log = $a->getLogger();
return $this;
}
}
(new A)->withLogger((default)->log('B'));
@coogle
Copy link
Author

coogle commented Aug 27, 2024

The reason this is problematic is because class A's owner today could swap $a = new DatabaseLogger for $a = LoggerType::DB and downstream no callers code would break. With the RFC being proposed on default that would no longer be the case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment