我试图在抽象类方法上有一个很好的练习,所以我创建了一个简单的curl包装类但不幸的是它不起作用。
抽象
<?php
abstract class curl{
private $url;
public function __construct($url){
$this->url = $url ;
}
public function curl_grab_page()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
ob_start(); // prevent any output
return curl_exec ($ch); // execute the curl command
ob_end_clean(); // stop preventing output
curl_close ($ch);
}
public abstract function getHTML();
}
?>
子
<?php
class google extends curl{
private $url;
function __construct($url) {
parent::__construct($url);
}
function curl_grab_page(){
parent::curl_grab_page();
}
function getHTML(){
return $this->curl_grab_page();
}
}
这就是我在头版中打电话的方式。
<?php
include 'classes/class.curl.php';
include 'classes/class.google.php';
$google = new google('http://www.google.com/');
echo $google->getHTML();
?>
它没有打印出任何东西 我单独尝试了这个功能,它很顺利
答案 0 :(得分:1)
看起来你没有在调用return之前本地化输出缓冲区的结果,试试这个:
public function curl_grab_page()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
// Don't need any output buffering b/c you set CURLOPT_RETURNTRANSFER to true, which means the results will be returned via curl_exec
//ob_start(); // prevent any output
//return curl_exec ($ch); // execute the curl command
//ob_end_clean(); // stop preventing output
$contents = curl_exec($ch);
curl_close ($ch);
return $contents;
}
孩子班:
<?php
class google extends curl{
// Don't need this, if you set the parent's scope to protected which means child class has access
// private $url;
function __construct($url) {
parent::__construct($url);
}
// Don't really need this method unless you plan on doing some custom logic
function curl_grab_page(){
// If you keep this method I added a return here so we can get the results of the call
return parent::curl_grab_page();
}
function getHTML(){
return $this->curl_grab_page();
}
}