How can the Singleton pattern be implemented in PHP to access array values stored in a class instance?

To implement the Singleton pattern in PHP to access array values stored in a class instance, we can create a static method within the class that returns the single instance of the class. This ensures that only one instance of the class is created and allows us to access the array values stored in that instance.

class Singleton {
    private static $instance;
    private $data = [];

    private function __construct() {}

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }

    public function setData($key, $value) {
        $this->data[$key] = $value;
    }

    public function getData($key) {
        return $this->data[$key];
    }
}

// Usage
$singleton = Singleton::getInstance();
$singleton->setData('key', 'value');
echo $singleton->getData('key');