我有两个php文件,一个管理数据库连接,另一个从数据库中检索数据。我从头开始写这个作为学习经验,并且授予它是凌晨5点但由于某种原因我无法访问我需要的变量。
我的数据库连接文件如下:
<?
class mysqlManager {
var $dbhost = 'xxx.xxx.xxx.xxx';
var $dbuser = 'xxx';
var $dbpass = 'xxx';
var $dbname = 'xxx';
var $connection;
var $errorCode;
var $errorMsg;
public function __construct($host='',$user='',$pass='',$name='') {
if(!$host=='') $this->dbhost = $host;
if(!$user=='') $this->dbuser = $user;
if(!$pass=='') $this->dbpass = $pass;
if(!$name=='') $this->dbname = $name;
}
function openConnection($host,$user,$pass) {
if(!$this->connection = @mysql_connect($host,$user,$pass,true)) {
$this->errorCode = mysql_errno();
$this->errorMsg = mysql_error();
return false;
}
return true;
}
function closeConnection() {
if($this->connection){
@mysql_close($this->connection);
}
}
function selectDB($name) {
if(!$this->openConnection($this->dbhost,$this->dbuser,$this->dbpass)){
return false;
}else{
return @mysql_select_db($name);
}
}
}
?>
获取数据的下一个文件如下:
<?
class ccp {
var $mgr;
public function __construct() {
$this->mgr = new mysqlManager();
}
public function test() {
print_r($this->mgr);
}
function getCCP() {
if($mgr->openConnection($mgr->dbhost,$mgr->dbuser,$mgr->dbpass)) {
if(!$mgr->selectDB($mgr->dbname)) {
$mgr->closeConnection();
return 'An error has occured while processing your request.';
}
$q = 'SELECT * FROM ccp WHERE cat="ccp" ORDER BY date DESC';
$r = @mysql_query($q);
$ret='';
while($row = @mysql_fetch_array($r)){
$ret = '<div class="post">';
$ret .= ' <h2 class="title">'.$row["title"].'</h2>';
$ret .= ' <p class="date">'.$row["date"].'</p>';
$ret .= ' <div class="entry">'.$row["body"].'</div>';
$ret .= '</div>';
}
$mgr->closeConnection();
return $ret;
}
}
}
?>
当我运行测试功能时,我得到了这个:
mysqlManager Object ( [dbhost] => xxx.xxx.xxx.xxx [dbuser] => xxx [dbpass] => xxx [dbname] => xxx [connection] => [errorCode] => [errorMsg] => )
如何访问mysqlManager对象中的变量?
谢谢!
答案 0 :(得分:2)
要访问对象的成员,请多次使用->
和嵌套对象。所以:在test()中:
echo $this->mgr->dbhost; // echoes xxx.xx.xxx.xxx
echo $this->mgr->dbpass; // echoes xxx
您可以这样做,因为变量是使用var
声明的,因此隐式公开。如果您使用private
或protected
声明它们,请执行以下操作:
class mysqlManager
{
private $dbhost = 'xxx.xxx.xxx.xxx';
protected $dbuser = 'xxx';
...
您将无法访问其他对象的变量。
这会回答你的问题吗?