问题
Is it possible to create a connection in a PHP class file and use it in all of the different methods in the class? I am trying to open a connection in the constructor and i get an error when i get to the close connection method saying that the argument that I've provided in the mysql_close() statement isn't a valid MYSQL-Link souce.
Update: Ok I figured it out I had a variable misspelled.
回答1:
It is entirely possible, you just need to make the database link a class member:
class MyDBClass {
var $sth;
function __construct($host, $user, $pass) {
$this->sth = mysql_connect($host, $user, $pass);
}
function close() {
mysql_close($this->sth);
}
}
回答2:
As long as the variable has the correct scope, it should work fine through the whole class. One way to do this would be to store the connection as a member variable, e.g.
$this->connection = mysql_connect(...);
This will make it visible to all class methods as long as you use the same method to retrieve it, e.g.
mysql_close($this->connection);
来源:https://stackoverflow.com/questions/978478/php-and-mysql-connections