get_status() 函数返回 1 而不是 true 或 false,为什么?

Ben*_*ton 2 php oop class

在下面的代码中,我的网站类中的 get_status() 方法返回 1 而不是我想要的 true 或 false。谁能告诉我为什么?我认为这可能是我班上的一个错误,我不确定这行代码是否是 get_status() 方法中的好习惯?

$httpcode = $this->get_httpcode();

当我回显 $siteUp 时,无论我将 url 设为http://www.google.com还是http://www.dsfdsfsdsdfsdfsdf.com,它始终为 1

我对面向对象的 php 还很陌生,这是我第一次自学,这是我正在构建的一个学习 oop 的例子。它旨在检查网站状态并根据 httpcode 判断它是启动还是关闭。

您对为什么这不起作用的任何提示都将大受欢迎。提前致谢!

class website {
protected $url;

function __construct($url) {
    $this->url = $url;
}

public function get_url() {
    return $this->url;
}

public function get_httpcode() {
    //get the http status code
    $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
    $ch=curl_init();
    curl_setopt ($ch, CURLOPT_URL,$this->url);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_VERBOSE,false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSLVERSION, 3);
    $page=curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $httpcode;
}

public function get_status() {
    $httpcode = $this->get_httpcode();
    if ($httpcode>=200 && $httpcode<400) {
         $siteUp = true;
    } else {
        $siteUp = false;
    }
    return $siteUp;
}
}

// create an instance of the website class and pass the url
$website = new website("http://www.google.com");
$url = $website->get_url();
$httpcode = $website->get_httpcode();
$siteUp = $website->get_status();
echo "site up is set to: " . $siteUp;
Run Code Online (Sandbox Code Playgroud)

moo*_*pet 5

1 就是 PHP 将“true”转换为字符串的方式

<?php echo true; ?>
Run Code Online (Sandbox Code Playgroud)

将显示 1。

在 PHP 中,针对 1 的测试和针对 true 的测试几乎是一回事。

$siteUp = $website->get_status() ? "true" : "false";
Run Code Online (Sandbox Code Playgroud)

将使它成为一个字符串供您显示...但是您无法针对它进行测试以验证其真实性,因为“true”和“false”都是有效的字符串,并且会给您一个布尔值 TRUE。