在静态类中使用 require_once
我需要 PHPCassa 项目中的两个类到我的类中。在将类设为静态之前,我能够调用 selectColumnFamily 中的方法。但现在不行了。有办法解决这个问题吗?这也是最好的策略吗?我只是希望不必每次都重新连接到 Cassandra DB。那么如果我使用 CASSANDRA:: 它只会连接一次还是多次?
预先感谢您的任何帮助。
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 ColumnFamily(self::$pool, $column_family_name);
}
}
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 ColumnFamily(self::$pool, $column_family_name);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,首先您使用 $this 来访问静态变量,这是错误的:
您应该使用
self::
而不是$this->
。但主要问题是:使用类的静态方法时不会调用构造函数!(好吧,除非您之前执行了
new CASSANDRA()
,但是那这样做是没有意义的)。在这里,您在构造函数中设置了连接,但如果您不调用它,则
selectColumnFamily
将失败,因为它将尝试使用未设置的连接。解决此问题的快速方法是将 __construct() 方法重命名为 static init() ,并在使用该类时执行此操作:
但我强烈建议您阅读很好的教程,正确使用 OOP,使用对象而不是静态类。
Ok first you are using $this to access static variables, this is wrong:
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 tostatic init()
, and do that when using the class:But I highly encourage you to read a good tutorial and use OOP correctly, using objects and not static classes.