From ac57fcfd32d716a53efc24d936d8d67dbc2faffa Mon Sep 17 00:00:00 2001 From: Sebastian Meyer Date: Sat, 11 Nov 2023 20:06:53 +0100 Subject: [PATCH] Use late static binding in traits --- src/Traits/Getter.php | 6 +++--- src/Traits/Setter.php | 6 +++--- src/Traits/Singleton.php | 10 ++++++---- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/Traits/Getter.php b/src/Traits/Getter.php index 184d568..dd0a2fa 100644 --- a/src/Traits/Getter.php +++ b/src/Traits/Getter.php @@ -45,12 +45,12 @@ trait Getter { $method = 'magicGet' . ucfirst($property); if ( - property_exists(get_called_class(), $property) - && method_exists(get_called_class(), $method) + property_exists(static::class, $property) + && method_exists(static::class, $method) ) { return $this->$method(); } else { - throw new InvalidArgumentException('Invalid property or missing getter method for property: ' . get_called_class() . '->' . $property . '.'); + throw new InvalidArgumentException('Invalid property or missing getter method for property: ' . static::class . '->' . $property . '.'); } } diff --git a/src/Traits/Setter.php b/src/Traits/Setter.php index a1d8734..a316a34 100644 --- a/src/Traits/Setter.php +++ b/src/Traits/Setter.php @@ -46,12 +46,12 @@ trait Setter { $method = 'magicSet' . ucfirst($property); if ( - property_exists(get_called_class(), $property) - && method_exists(get_called_class(), $method) + property_exists(static::class, $property) + && method_exists(static::class, $method) ) { $this->$method($value); } else { - throw new InvalidArgumentException('Invalid property or missing setter method for property: ' . get_called_class() . '->' . $property . '.'); + throw new InvalidArgumentException('Invalid property or missing setter method for property: ' . static::class . '->' . $property . '.'); } } diff --git a/src/Traits/Singleton.php b/src/Traits/Singleton.php index 2379c84..8e0da1b 100644 --- a/src/Traits/Singleton.php +++ b/src/Traits/Singleton.php @@ -40,20 +40,22 @@ trait Singleton * * @param mixed ...$args Parameters for the constructor */ - public static function getInstance(mixed ...$args): self + final public static function getInstance(mixed ...$args): static { $class = static::class; if (!isset(static::$singleton[$class])) { - static::$singleton[$class] = new $class(...$args); + static::$singleton[$class] = new static(...$args); } return static::$singleton[$class]; } /** - * This is a singleton class, thus the constructor is protected. + * This is a singleton class, thus the constructor is private. * (Get an instance of this class by calling self::getInstance()) + * + * @param mixed ...$args Parameters for the constructor */ - abstract protected function __construct(); + abstract private function __construct(mixed ...$args); /** * This is a singleton class, thus cloning is prohibited.