我正在尝试为项目创建单例DAO类,但我无法弄清楚为什么getInstance方法未定义。
我收到此错误:
" project / read.php:37:致命错误:调用未定义的方法MiteDAO :: getInstance"
另外,我在Tomcat8上用Quercus运行它,在哪里可以找到打印堆栈跟踪的日志?我想我今天在日志目录中检查了所有内容,但我没有看到它。
(这是我第一次这样做)
此脚本在提交
的前端调用<?php
ob_start();
ini_set('display_errors', 'On');
include 'MiteDAO.php';
include 'Contributer.php';
//FORM VALUES
$_cname = $_POST['cname'];
$_sname = $_POST['sname'];
$_sdate = $_POST['sdate'];
$_edate = $_POST['edate'];
$db_read_query = "select *
from contributes
where cname = '{$_cname}' and
sname = '{$_sname}' and
cdate > '{$_sdate}' and
cdate < '{$_edate}';";
echo "<p> From $_sdate to $_edate, $_cname made the following contributions to Senator $_sname </p>";
$db_dao = MiteDAO::getInstance();
$results = $db_dao->query($db_read_query);
$Contributers[];
while ($row = pg_fetch_row($result)) {
$temp_contrib = new Contributer();
$temp_contrib->sname = $row[0];
$temp_contrib->cname = $row[1];
$temp_contrib->cdate = $row[2];
$temp_contrib->amt = $row[3];
array_push (Contributers, $temp_contrib);
}
echo array_values(Contributers); //TODO
?>
这是定义了getInstance的MiteDAO类
<?php
class MiteDAO {
private static $instance;
private $conn;
public static function getInstance() {
if ($instance === null) {
self::$instance = new MiteDAO();
}
return self::$instance;
}
public function connect() {
$conn = pg_connect ("host=localhost
port=5432
dbname=postgres
user=shepard
password=p4ssw0rd
connect_timeout=5")
or die ("connection failed");
}
public function close() {
pg_close ($conn);
}
public static function query($query) {
return pg_query ($conn, $query) or die ('Query failed');
}
}
?>
目前..这两个文件位于同一目录
答案 0 :(得分:4)
您需要使用self::
if (is_null(self::$instance)) {
self::$instance = new MiteDAO();
}
return self::$instance;
http://php.net/manual/en/language.oop5.static.php
编辑
您的主脚本中有错误:
致命错误:无法在第26行的/project/read.php中使用[]进行阅读
如果您正在尝试创建阵列,则需要执行以下操作:
$contributors = array(); // use lower case for variable names, too
这也无效:
array_push (Contributers, $temp_contrib); // Reference your variable with a $