Php析构函数被调用了两次
我搜索了很多,发现了很多与我类似的问题,但没有找到我在哪里建立了我的awnser,所以我在这里提问 我有以下代码Php析构函数被调用了两次,php,mysql,Php,Mysql,我搜索了很多,发现了很多与我类似的问题,但没有找到我在哪里建立了我的awnser,所以我在这里提问 我有以下代码 class Checkout { static $dbCon = null; private $CheckoutId = null; public function __construct() { echo"Contructor"; // Check if have an checkout already $Prepare = Checkout::$db
class Checkout
{
static $dbCon = null;
private $CheckoutId = null;
public function __construct()
{
echo"Contructor";
// Check if have an checkout already
$Prepare = Checkout::$dbCon ->prepare("SELECT * FROM checkouts WHERE SessionId = :SessionId AND LastTouchTime >= :Time ORDER BY Id DESC");
$Prepare -> bindValue(':SessionId',session_id());
$Prepare -> bindValue(':Time',0); // Will be something like time()-(60*60*2)
try{
$Prepare -> execute();
if($Prepare -> rowCount() != 0)
{
$Checkout = $Prepare->fetch(PDO::FETCH_ASSOC);
$ThisVar = unserialize($Checkout['ObjectSerialized']);
foreach($ThisVar as $Key => $Val)
$this->$Key = $Val;
$this->CheckoutId = $Checkout['Id'];
echo " -> $this->CheckoutId\n";
}
}catch(PDOException $e)
{ die("Error Getting checkout From Db: ".$e->getMessage()); }
}
public function __destruct()
{
echo "Destructor -> ".(is_null($this->CheckoutId)?'Null':$this->CheckoutId)."\n";
if(is_null($this->CheckoutId))
{// Insert Checkout In db
$InsertCheckout = Checkout::$dbCon->prepare("INSERT INTO checkouts (`SessionId`,`LastTouchTime`,`ObjectSerialized`) VALUES(:SessionId,:LastTouchTime,:ObjectSer);");
$InsertCheckout -> bindValue(':SessionId',session_id());
$InsertCheckout -> bindValue(':LastTouchTime',time());
$InsertCheckout -> bindValue(':ObjectSer',serialize($this));
try{
$InsertCheckout -> execute();
echo "Just Inserted Checkout\n";
}catch(PDOException $e)
{
die("Error SavingCart In Db: ".$e->getMessage());
}
}
else
{
//$UpdateCheckout = Checkout::$dbCon->prepare("");
}
}
}
我像下面这样初始化这个类
Checkout::$dbCon = new $PDOObject; ( is valid )
$Checkout = new Checkout();
我得到的结果是一些漂亮的东西
Contructor -> 142
Destructor -> Null
Just Inserted Checkout
Destructor -> 142
您可以看到,如果construct回显一个数字,这意味着该数字在$this->$CheckoutId中
但是析构函数运行时,$CheckoutId中没有数字,因此它会重新插入一条新记录
然后析构函数再次运行,这次他有一个数字,所以它将尝试更新记录
有什么我错过的吗
编辑
如果我注释行$ThisVar=unserialize($Checkout['ObjectSerialized'])代码>
它不会无缘无故地运行析构函数
为什么?谢谢你的建设性评论,但我昨天已经看了这个问题,当时我确实尝试删除这个设置,但它仍然存在:/I我刚刚意识到,当我注释掉行$ThisVar=unserialize($Checkout['ObjectSerialized');它按预期工作?