Php “错误”;不在对象上下文中使用$this“;有课
我有一门课是这样的:Php “错误”;不在对象上下文中使用$this“;有课,php,Php,我有一门课是这样的: <?php class DataConnection { private $hostName = "localhost"; private $username = "root"; private $password = ""; private $dbName = "test"; private $link = ""; public function __cons
<?php
class DataConnection {
private $hostName = "localhost";
private $username = "root";
private $password = "";
private $dbName = "test";
private $link = "";
public function __construct() {
}
private function connect() {
$this->link = mysql_connect($this->hostName, $this->username, $this->password)
or die ("Could not connect to the database");
mysql_select_db($this->dbName, $this->link) or die("Could not select database");
}
// lay kieu du lieu cua record trong table
public function getDataTypeTable($tableName) {
$this->connect();// ERROR HERE
$query = "SELECT * FROM {$tableName}";
$result = mysql_query($query);
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
//var_dump($results);
//mysql_free_result($results);
}
public function __destruct() {
mysql_close($this->link);
}
}
?>
如何调用getDataTypeTable
?您可以将connect()
函数声明为静态函数,然后像DataConnection::connect()
那样调用它,我认为它应该可以工作。真的很抱歉。我应该像$dataConnection->getDataTypeTable(“abc”)一样调用这个类;取而代之的是DataConnection::getDataTypeTable(“abc”)@基勒黑尔:是的。您需要->
。没有它,您将静态调用它,因此,$this
不存在,因为您没有在实例上调用它。