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


get_status() function returns 1 instead of true or false, why?

在下面的代码中,我的网站类中的get_status()方法返回1,而不是像我希望的那样返回true或false。有人能告诉我为什么吗?我认为这可能是我的类中的一个错误,我不确定这行代码在get_status()方法中是否是好的实践?

$httpcode=$this->get_httpcode();

当我回显$siteUp时,无论我是否将url设置为http://www.google.com或http://www.dsfdsfsdsdfsdfsdf.com

我对面向对象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;

1就是PHP如何将"true"转换为字符串

<?php echo true; ?>

将显示1。

在PHP中,对1进行测试和对true进行测试基本上是一样的。

$siteUp = $website->get_status() ? "true" : "false";

将使其成为字符串供您显示。。。但是您不能针对它来测试真值,因为"true"answers"false"都是有效的字符串,并且会给您一个布尔值true。

您将返回一个布尔值,它是TRUEFALSE(但不是单词true或false)。

您可以返回字符串,也可以在将其附加到echo语句之前对其进行转换:

例如:

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

或者,如果您想将其保留为返回的布尔值,您可以使用一个非常简单的函数将其转换为如下字符串:

public function showBool($myBool)
{
    return ($myBool) ? 'True' : 'False';
}
$someVar=false;
echo showBool($someVar);

作为一个简单的练习,试着运行下面的代码,自己看看:

<?php 
    echo true;
?>

您要做的是打印一个布尔值,并期望字符串"true"或"false"。你可以做一些类似的事情:

$booleanVal? "true":"false";

避免打印出true/false。使用if语句查看它实际返回的内容。您希望$siteUp打印什么?

if($siteUp) { 
    echo "Up"; 
} else { 
    echo "Down"; 
}