【问题标题】:Does calling curl_close inside the destructor work?在析构函数中调用 curl_close 是否有效?
【发布时间】:2014-10-19 02:30:07
【问题描述】:

简单的问题;我在我的一个抽象 PHP 类中执行以下操作,但我不知道它是否真的被调用/做任何事情:

abstract class Curl {

    protected $curl;

    public function __construct()
    {
        $this->curl = curl_init();
    }

    public function __destruct()
    {
        curl_close($this->curl);
    }
}

我已经阅读了关于 __destruct 是否真的被调用的各种在线帖子,所以我想知道这是否是我应该做的事情?

【问题讨论】:

  • php 在脚本退出时自行清理。唯一需要显式关闭 curl 句柄的情况是,如果您在循环中使用大量 curl 并初始化新的 curl 是恢复“正常”选项/配置的最简单方法。
  • 根据这个 QA,目前还不清楚是否绝对保证在每种情况下都会调用析构函数:stackoverflow.com/questions/151660/… - 我个人会在每次 curl 操作后调用 curl_close,而不是在类析构函数中.

标签: php curl


【解决方案1】:

由于没有初始化,所以不调用__destruct:

<?php

class test
{
    static $t = null;
}

abstract class Curl {

    protected $curl;

    public function __construct()
    {
        $this->curl = curl_init();
    }

    public function __destruct()
    {
        var_dump( curl_close( $this->curl ) );
        test::$t = curl_close( $this->curl );
    }
}

class ConcreteClass extends Curl
{

}
var_dump( test::$t );

?>

【讨论】:

  • 为了澄清 OP,您需要具体的类在自己的析构函数中调用 parent::__destruct(),因为子类不会从父类继承构造函数/析构函数方法。
猜你喜欢
  • 2011-08-27
  • 2013-06-25
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 2012-03-18
  • 1970-01-01
相关资源
最近更新 更多