[英]get_status() function returns 1 instead of true or false, why?
在下面的代码中,我的网站类中的get_status()方法返回1而不是像我想要的那样返回true或false。 有谁能告诉我为什么好吗? 我认为这可能是我班上的一个错误,我不确定这行代码是否是get_status()方法中的好习惯?
$ httpcode = $ this-> get_httpcode();
当我回显$ siteUp时,无论我将网址设为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;
1是PHP如何将“true”转换为字符串
<?php echo true; ?>
将显示1。
在PHP中,针对1的测试和针对true的测试大多是相同的。
$siteUp = $website->get_status() ? "true" : "false";
将它作为一个字符串供你显示...但是你无法测试它的真相,因为“true”和“false”都是有效的字符串并且会给你一个布尔值TRUE。
您将返回一个布尔值,该值为TRUE
或FALSE
(但不是单词 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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.