Search code examples
phpstatic-functions

php static function run twice


I am new in studing php static function I want to build a function, curl some contents from some url, and then process php regex to get what I need. Here is my code, but the curl part runs twice. How to modify it so that short the run durante?

$url = 'www.php.net/archive/2012.php';
if (!$url){
    exit;
}
echo TestClass::getTitle1($url);
echo '<hr />';
echo TestClass::getTitle2($url);
class TestClass
{
    static function getTitle1($url)
    {
        $data = self::getHtml($url);// run in first time
        preg_match("/(<h1.*>)(.*)(<\/h1>)/",$data,$h1tags); 
        $h1 =  $h1tags[0];
        if (!$h1) return false;
        return $h1;
    }
    static function getTitle2($url)
    {
        $data = self::getHtml($url);// run in second time
        preg_match("/(<h2.*>)(.*)(<\/h2>)/",$data,$h2tags); 
        $h2 =  $h2tags[0];
        if (!$h2) return false;
        return $h2;
    }
    static function getHtml($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $htmls = curl_exec($ch);
        curl_close($ch);
        if (!$htmls) return false;
        return $htmls;
    }
}

Solution

  • Like commented pass h1/h2 as a parameter to your function and rewrite your replace function. Or run curl outside and pass the result to your replace function.