Created
August 27, 2024 03:48
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ondefault
that would no longer be the case.