开发者

How do i check to see if an object has already been instantiated?

Is it possible to check and see if an object has already been instantiated with php? I have a mysql class that other pages instantiate to use its methods and what i did was make a log开发者_运维问答 that logs all queries. I noticed that mysql is opened 3-4 times at a time rather than one. So i need to verify if the object is instantiated and if not it wont create another one and open another useless connection.


Sounds like a perfect case for the Singleton pattern.

class Connection
{
    /**
     * @var Connection
     */
    private static $instance;

    private static $config = array();

    private function __construct()
    {
        // whatever you need in here, just keep the method private
    }

    public function __clone()
    {
        throw new RuntimeException;
    }

    public function __wakeup()
    {
        throw new RuntimeException;
    }

    public static setConfig(array $config)
    {
        self::$config = $config;
    }

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


You are looking for a singleton


You can use the instanceof operator to check if a given variable is of a specific class:

if ($db instanceof DatabaseClass) :

Read more about it here: http://php.net/instanceof


Simply use is_object, as an a class has no type but just has memory allocation, so using is_object on a class name will only return a string, when you instantiate an object by using the new keyword, and object is created in the memory and has it's objective type.

Test Case:

class HelloWorld{}

$a = is_object(HelloWorld);
$b = is_object(new HelloWorld);

var_dump($a, $b);

Results:

bool(false) bool(true)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜