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.
php static function run twice
-
28-11-2021 - |
Frage
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;
}
}
Lösung
Andere Tipps
Like the others told you, do not repeat yourself and use parameters.
But incase you need the method for another class you may use in the future (use one-time called data in more than one different function) i have edited it for you
<?php
class TestClass{
protected static $data;
static function getTitle1($url){
//check if $data is set or not
$data = self::$data ? self::$data : self::getHtml($url);
//do your code here
preg_match("/(<h1.*>)(.*)(<\/h1>)/",$data,$h1tags);
$h1 = $h1tags[0];
if (!$h1) return false;
return $h1;
}
static function getTitle2($url){
//check if $data is set or not
$data = self::$data ? self::$data : self::getHtml($url);
//do your code here
preg_match("/(<h1.*>)(.*)(<\/h1>)/",$data,$h1tags);
$h1 = $h1tags[0];
if (!$h1) return false;
return $h1;
}
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;
//ADD THIS LINE TO YOUR CODE AS WELL
self::$data = $htmls;
return $htmls;
}
}
$url = 'www.php.net/archive/2012.php';
$class = new TestClass();
echo $class->getTitle1($url);
echo '<hr />';
echo $class->getTitle2($url);
?>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow