我有一堂这样的课:
class Session {
private Session_Database $db;
public function __construct(){
// Instantiate new Database object
$this->db = new Session_Database();
// Set handler to overide SESSION
session_set_save_handler(
[$this, '_open'],
[$this, '_close'],
[$this, '_read'],
[$this, '_write'],
[$this, '_destroy'],
[$this, '_gc']
);
// Start the session
session_start();
}
/* ... */
public function _close(): bool {
// Close the database connection
$this->db->close();
return true;
}
/* ... */
}
我在日志中看到此错误:
PHP 致命错误:未捕获错误:无法访问私有属性
,位于 [行号Session::$db
]$this->db->close()
堆栈跟踪:
#0【内部功能】:Session->_close()
#1 {主要} 扔进去...
但是,当我通过在 xdebug 中单步执行来测试代码时,它会按预期工作。
发生什么事了?
如果在 PDO 查询过程中内存耗尽,就会出现这种情况。我相信这与 PDO 缓冲查询使用的内存以及 PHP 内部代码在内存耗尽后释放内存的方式有关。
我可以使用以下代码重现您遇到的情况,(注意:这是使用
register_shutdown_function
。session_close 代码和 register_shutdown_function
都将在内存耗尽错误后运行):
<?php
class TestingClass
{
private int $something_private;
public function getThisDone(): void
{
$this->something_private = 0;
}
}
// get a reference to the testing class
$obj = new TestingClass();
register_shutdown_function(fn() => $obj->getThisDone());
// get a pdo connection and run a query that returns a lot of data
$pdoConnection = get_db_read_connection();
$pdoStatement = $pdoConnection->prepare('SELECT * FROM your_table_with_a_lot_of_records LIMIT 100000');
$results = $pdoStatement->fetchAll(PDO::FETCH_CLASS, '\stdClass');
以及由此产生的致命错误:
如果我只是通过字符串连接触发内存不足错误,则无法重现该错误,如下所示。
// use code above but replace pdo connection and query with this
while(true)
{
$data .= str_repeat('#', PHP_INT_MAX);
}
我认为不应该。看起来这是 PHP 错误报告的一个很好的候选者。