PHP code example of okapi / singleton

1. Go to this page and download the library: Download okapi/singleton library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

okapi / singleton example snippets




use Okapi\Singleton\Singleton;

class GovernmentOfUSA
{
    // Add the singleton trait
    use Singleton;
    
    /**
     * Function to register the singleton. 
     * 
     * This function and the "initialized" methods are completely optional.
     * 
     * Can be static or non-static. 
     */
    public static function register(): void
    {
        // Get instance
        $instance = self::getInstance();
        
        // For non-static just use $this
        
        // Make sure the instance is only registered once
        $instance->ensureNotInitialized();
        
        // Do something
        // ...
        
        // Mark the instance as initialized
        $instance->setInitialized();
    }
    
    /**
     * Custom function
     */
    public function takeOverTheWorld(): void
    {
        // Make sure the instance is initialized
        $this->ensureInitialized();
        
        // Do something
        // ...
    }
}

// Other file

// Register the singleton
GovernmentOfUSA::register();

// Take over the world
$instance = GovernmentOfUSA::getInstance();
$instance->takeOverTheWorld();
// or
GovernmentOfUSA::getInstance()->takeOverTheWorld();