我想在另一个类中使用一个类。
这是我的第一堂课:
class mydb {
public function connect($host="localhost",$user,$pass,$data,$persistency=False) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->data = $data;
$this->persistency = $persistency;
$this->link=@mysql_connect($this->host,$this->user,$this->pass)or die(mysql_error());
If(($this->link) AND ($this->data)) {
If(@mysql_select_db($this->data,$this->link) or die(mysql_error())) {
return True;
}
}
return False;
}
public function query($query="",$sup="") {
If($sup) {
$query=@mysql_query($query,$this->link)or die("<br /><br />".mysql_error()."<br /><br />");
} Else {
$query=@mysql_query($query,$this->link) or die("<br /><br />".mysql_error()."<br /><br />");
}
return($query);
}
}
这是我的第二堂课:
class articles {
function getpath($id) {
$sql=$db->query("select id,name from articles where id='$id'");
$row=mysql_fetch_array($sql);
return $row['name'];
}
}
我收到此错误:( Fatal error: Call to a member function query() )
答案 0 :(得分:2)
您没有在任何地方创建$db
。
答案 1 :(得分:0)
您需要在articles类中创建对mydb类的引用。假设你创建了一个mydb类的实例并将其存储在变量$ db中,这就是你要做的。
class articles {
public static $db = null;
...
self::$db->query(...);
}
articles::$db = $db;
变量不必是静态的,它可以是常规的类变量。然后你会像
那样引用它$this->db->query(...);
答案 2 :(得分:0)
如上所述,您需要mydb
类的实例可供articles
使用。
这是一个简单的例子(也许是anti-pattern):
class articles {
private $db = null; // add a class property to hold your database object
// each time we create an articles object, we'll connect to the database
public function __construct() {
$this->db = new mydb(); // add your connection params
}
public function getpath($id) {
// now we can reference the object via the class property $this->db
$sql = $this->db->query("select id,name from articles where id='$id'");
$row = mysql_fetch_array($sql);
return $row['name'];
}
// the rest of your code goes here
}
如果您不想不断创建新的mydb
个实例,您可以做一些稍微不同的事情:
class articles {
private $db = null;
// Here we'll use an existing mydb object and pass it into our new articles
public function __construct(mydb $db) {
$this->db = $db;
}
// the rest of your code goes here
}
$db = new mydb(); // create mydb
$db->connect(); // add your params
$articles = new articles($db); // create articles using mydb from above
class mydb {
// This is static, which is special
private static $instance = null;
public static function setInstance(mydb $db) {
self::$instance = $db;
}
public static function getInstance(mydb $db) {
return self::$instance;
}
// the rest of your code goes here
}
$db = new mydb(); // Create a mydb object
$db->connect(); // add your params
mydb::setInstance($db); // store the mydb object in the mydb class
// Later when you want to query we use the stored object:
// (and this will now work everywhere in the program--
// we don't need $db anymore)
mydb::getInstance()->query();
通常,您不希望打开或维护与数据库的多个连接。在任何地方使用相同的连接速度更快。但有时候这不合适。
单身人士是服务定位器的廉价形式。你创建一个资源(或“服务”)然后你有办法找到该资源而不传递变量。单身人士是一个基本的解决方案,但有更好的方法来构建您的应用程序。
您可能想了解两个相关的设计模式:服务定位器和依赖注入。两者都在这里描述:http://martinfowler.com/articles/injection.html