<?php
trait Singleton
{
private static ?object $instance = null;
public static function GetInstance(): object {
// Reflection better here for Dependency Injection into the instance
return self::$instance ?? (self::$instance = new self());
}
public function __set(string $property, string $value) {
$this->{$property} = $value;
}
public function __get(string $property): mixed {
return $this->{$property} ?? null;
}
protected function __construct() {}
private function __clone() {}
}
class User
{
use Singleton;
protected function __construct() {
// Change this to the select inner join query
foreach(['id' => 1, 'column' => 'test', 'points' => 3] as $column => $value)
$this->$column = $value;
}
public function save(): mixed {
// Change this to an update query
return get_object_vars($this);
}
}
User::getInstance()->points = 5; // Dynamically change values
var_dump(User::getInstance()->save()); // Then update
Deprecated: Creation of dynamic property User::$id is deprecated in /in/3WrMs on line 13
Deprecated: Creation of dynamic property User::$column is deprecated in /in/3WrMs on line 13
Deprecated: Creation of dynamic property User::$points is deprecated in /in/3WrMs on line 13
array(3) {
["id"]=>
string(1) "1"
["column"]=>
string(4) "test"
["points"]=>
int(5)
}
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Deprecated: Creation of dynamic property User::$id is deprecated in /in/3WrMs on line 13
Deprecated: Creation of dynamic property User::$column is deprecated in /in/3WrMs on line 13
Deprecated: Creation of dynamic property User::$points is deprecated in /in/3WrMs on line 13
array(3) {
["id"]=>
string(1) "1"
["column"]=>
string(4) "test"
["points"]=>
int(5)
}
Fatal error: Uncaught TypeError: Return value of User::save() must be an instance of mixed, array returned in /in/3WrMs:36
Stack trace:
#0 /in/3WrMs(41): User->save()
#1 {main}
thrown in /in/3WrMs on line 36
Process exited with code 255.
Output for 7.3.0 - 7.3.33
Parse error: syntax error, unexpected '?', expecting function (T_FUNCTION) or const (T_CONST) in /in/3WrMs on line 5
Process exited with code 255.