开发者

Using require_once in a static class

I am requiring two classes from the PHPCassa project into my class. Before I made my Class static I was able to call the method in selectColumnFamily. But now it does not work. Is there a way around this? Also is this the best strategy? I just want to be able to not have to re-connect to the Cassandra DB every time. So if I use CASSANDRA:: will it only connect once or multiple times?

Thanks in advance for any help.

class CASSANDRA {

    protected static $config = array();
    protected static $keyspace = NULL;
    protected static $servers = array();
    public static $pool = NULL;

    public function __construct()
    {

        require_once ('phpcassa/connection.php');
        require_once ('phpcassa/columnfamily.php');

        // Test the config group name
        $config = Kohana::config('cassandra');

        self::$servers = $config['servers'];
        self::$keyspace = $config['keyspace'];

        self::$pool = new ConnectionPool($this->keyspace, $this->servers);

    }

    public static function selectColumnFamily($column_family_name)
    {

        return new ColumnFa开发者_如何转开发mily(self::$pool, $column_family_name);

    }

}


Ok first you are using $this to access static variables, this is wrong:

self::$pool = new ConnectionPool($this->keyspace, $this->servers);

You should use self:: instead of $this->.

But the main problem is: the constructor is not called when using the static methods of a class! (well, unless you did a new CASSANDRA() just before, but that makes no sense to do that).

Here, you setup the connection in the constructor, but if you don't call it, then selectColumnFamily will fail because it will try to use a connection not set.

A quick way to fix that is to rename the __construct() method to static init(), and do that when using the class:

CASSANDRA::init();
$foo = CASSANDRA::selectColumnFamily(...);

But I highly encourage you to read a good tutorial and use OOP correctly, using objects and not static classes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜