php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #78451 No possibility make Singleton in the PHP
Submitted: 2019-08-24 11:56 UTC Modified: 2019-08-24 16:53 UTC
From: forziforzi at gmail dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 7.3.8 OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: forziforzi at gmail dot com
New email:
PHP Version: OS:

 

 [2019-08-24 11:56 UTC] forziforzi at gmail dot com
Description:
------------
---
From manual page: https://php.net/class.closure
---

So, no Singleton in the PHP!

Test script:
---------------
<?php

final class A {
    private function __construct() {}
    private function __clone() {
        throw new \Exception('Singleton');
    }
    private function __sleep() {
        throw new \Exception('Singleton');
    }
    private function __wakeup() {
        throw new \Exception('Singleton');
    }
    public static function instantiate() {
        static $obj;
        return $obj = $obj ?? new self;
    }
}

$closure = function () {
    $class = get_class($this);
    return new $class;
};

$obj = A::instantiate();

var_dump($obj);
var_dump($closure->call($obj));



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-08-24 16:53 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2019-08-24 16:53 UTC] requinix@php.net
PHP allows you to shoot yourself in the foot if you wish.
 [2019-08-25 19:00 UTC] jasny@php.net
If you really care, you can do this;

<?php

final class A {
    static $obj;

    private function __construct() {
        if (isset(self::$obj)) {
            throw new \Exception('Singleton');
        }
        self::$obj = $this;
    }
    private function __clone() {
        throw new \Exception('Singleton');
    }
    private function __sleep() {
        throw new \Exception('Singleton');
    }
    private function __wakeup() {
        throw new \Exception('Singleton');
    }
    public static function instantiate() {
        return self::$obj ?? new self;
    }
}
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Wed Jul 08 01:01:25 2020 UTC