我有一个PDO数据库连接类,我在整个网站上使用它。
pdoConnect.php
class pdoConnect {
private $host = "localhost";
private $db = "database";
private $userSelect = "user";
private $passSelect = "XXXXX";
protected $selectInstance = true;
protected $options = [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
function dsn() {
return 'mysql:host=' . $this->host . ';dbname=' . $this->db;
}
function connectSelect() {
if ($this->selectInstance === true) {
$dsn = $this->dsn();
$this->selectConnect = new PDO($dsn, $this->userSelect, $this->passSelect,
$this->options);
}
return $this->selectConnect;
}
}
pagination.php
class pagination {
var $php_self;
var $rows_per_page = 10; //Number of records to display per page
var $total_rows = 0; //Total number of rows returned by the query
var $links_per_page = 5; //Number of links to display per page
var $append = ""; //Parameters to append to pagination links
var $sql = "";
var $debug = false;
var $conn = false;
var $page = 1;
var $max_pages = 0;
var $offset = 0;
var $multi = ""; //Use if multiple pagination instances are needed
function pagination($connection, $sql, $rows_per_page = 10,
$links_per_page = 5, $append = "", $multi = "") {
$this->conn = $connection;
$this->sql = $sql;
$this->rows_per_page = (int)$rows_per_page;
if (intval($links_per_page ) > 0) {
$this->links_per_page = (int)$links_per_page;
} else {
$this->links_per_page = 5;
}
$this->append = $append;
$this->multi = $multi;
$this->php_self = htmlspecialchars($_SERVER['PHP_SELF'] );
if (isset($_GET['page'] )) {
$this->page = intval($_GET['page'] );
}
}
function paginate(){
if ($this->sql != null) {
$all_rs = $this->conn->query($this->sql); //this is line 76
$this->total_rows = $all_rs->rowCount();
}
....
}
}
它可以在其他任何地方正常工作,但是,如果我实例化它,那么将它作为参数传递给另一个类,该对象不可访问。
require_once '/classes/pdoConnect.php';
$db = new pdoConnect();
$pdo = $db->connectSelect();
require_once '/classes/pagination.php';
$pages = new pagination( $pdo, $sql, $page_amount, 8, null );
然后我得到......
致命错误:在非对象中调用成员函数query() 第76行/classes/pagination.php
但是PDO连接对象存在!
var_dump($pdo);
object(PDO)#1 (0) { }
我唯一能想到的是,我已将pdoConnect
类扩展到另一个类,以便访问$selectInstance
属性。所以在我的IDE中,pdoConnect
类说is Overridden
。有人可以告诉我这里发生了什么吗?
答案 0 :(得分:1)
尝试更改function pagination( to function __construct(
__construct
和__destruct
是在实例化或销毁对象时随时调用(幕后)的特殊方法。如果要将参数作为对象实例化的一部分传递,则需要通过__construct
方法执行此操作。另一种方法是使用访问器:
$pages = new pagination;
$pages->setConn($pdo);
$pages->setSql($sql);
$pages->setRowsPerPage($page_amount);
....
您的pagination
函数不是访问者,它是一种用于以特定方式执行逻辑的包装器方法。访问者只是getters
和setters
的一个奇特术语。请考虑以下事项:
class Pagination
{
$conn = false; // This is a member variable
}
通常,您不希望允许外部代码直接设置类的成员变量的值,否则会破坏封装。相反,你想使用一个访问器,如下所示:
// somescript.php
$pager = new Pagination;
$pager->conn = $pdo; // Not a good practice
$pager->setConnection($pdo); // Setting the member variable through an accessor, preferred