开发者

Help with static class members

开发者 https://www.devze.com 2022-12-09 07:11 出处:网络
I have always used $this in my classes. Now I have to use a static class and I\'m lost. Can someone please tell me how to convert this to use static members? I\'ve tried to look at some tutorials but

I have always used $this in my classes. Now I have to use a static class and I'm lost. Can someone please tell me how to convert this to use static members? I've tried to look at some tutorials but they are not easy to understand. I also have no idea how to "instantiate" a static class so if someone could please provide an example, I'd be grateful.

Thanks.

class db
{
    private static $instance;
    private static $database_name;
    private static $database_user;
    private static $database_pass;
    pr开发者_开发百科ivate static $database_host;
    private static $database_link;

    private function db()
    {
        self::$database_name = "name";
        self::$database_user = "user";
        self::$database_pass = "password";
        self::$database_host = "host";
    }

    public static function getInstance()
    {
        if (!self::$instance)
        {
           ?????

          self::$instance = connect();
          return self::$database_link;
        }
        return self::$instance;
    }

    function dbLink()
    {
      self::$connect();
      return self::$database_link;
    }
...

EDIT:

Also, I'm really curious as to the advantages to using static classes over class members that can be used outside the class. I'd assume security but that's about it.


For a singleton you only make the getInstance() method static.

The key is to make the constructor private, so that the class can't be constructed anywhere but in getInstance(); from the manual:

<?php
class Example
{
    // Hold an instance of the class
    private static $instance;

    // A private constructor; prevents direct creation of object
    private function __construct() 
    {
        echo 'I am constructed';
    }

    // The singleton method
    public static function singleton() 
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }

    // Example method
    public function bark()
    {
        echo 'Woof!';
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

}

?>

The singleton pattern makes sure you only ever have one of something - for example database connections - which can be expensive to create.

You get your instance like this:

$myInstance = Example::getInstance();

This instance is a regular object - you you access the methods as normal (non-statically):

$myInstance->bark();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号