rfc:property-capture

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
rfc:property-capture [2023/04/22 21:16] imsoprfc:property-capture [2023/04/23 18:54] imsop
Line 155: Line 155:
 ===== Examples ===== ===== Examples =====
  
-**TODO**+**TODO - expand** 
 + 
 +Create a struct-like object with readonly public properties: 
 + 
 +<code php> 
 +$id = get_next_id(); 
 +$name = get_name(); 
 +$user = new readonly class use ($id, $name) {}; 
 +echo "{$user->id}: {$user->name}"; 
 +$user->id = 42; // ERROR: Cannot modify readonly property $id 
 +</code> 
 + 
 +Decorate a [[https://www.php-fig.org/psr/psr-3/|PSR-3]] logger, adding some context to all entries logged: 
 + 
 +<code php> 
 +use Psr\Log\{LoggerInterface,LoggerTrait}; 
 + 
 +function decorate_logger(LoggerInterface $logger, string $contextKey, mixed $contextValue): LoggerInterface { 
 +   return new class  
 +        use ($logger as private $innerLogger, $contextKey as private, $contextValue as private)  
 +        implements LoggerInterface 
 +   { 
 +        public function log($level, string|\Stringable $message, array $context = []): void { 
 +            $context[$this->contextKey] = $contextValue; 
 +            $this->innerLogger->log($level, $message, $context); 
 +        } 
 +   }; 
 +
 +</code>
  
 ===== Reflection ===== ===== Reflection =====
rfc/property-capture.txt · Last modified: 2023/04/23 21:15 by imsop