PHP/CI3 - 布尔值的类型转换无法按预期工作



我把我所有的网站设置都保存在一个名为mh_settings的表中。 mh_setting表有 2 个字段,即名称 varchar(255( 和类型 varchar(255(。

在核心文件夹和构造函数中的MY_Controller.php中,我将名称和键读取到 config_item(( 中,如下所示:

$appConfigOptions = $this->MH_settings_model->mh_get_configurations();
if($appConfigOptions) {
foreach($appConfigOptions as $appConfigOption)
{
$this->config->set_item($appConfigOption->key,$appConfigOption->value);
}
}

模型获取配置项,如下所示:

class MH_settings_model extends CI_Model {
protected $table;
public function __construct() {
$this->table = 'mh_settings';
}
public function mh_get_configurations() {
$query = $this->db->get($this->table);
return $query->result();
}
}

出于某种原因,即使我在 FALSE 的数据库中用值键入 cast mh_site_up_public,它似乎总是使其成为字符串。

if(((boolean) $this->config->item('mh_site_up_public')) ==  FALSE) {
show_error($this->config->item('mh_site_down_public_message'));
}

我尝试了(布尔(而不是(布尔(。

我尝试使用==和===

有什么想法吗?

由于表列是 varchar,因此mh_site_up_public将是一个字符串,其文字文本FALSE
非空字符串(或者如果它们只包含"0"(将被视为 true。

例:

var_dump((bool) '');
// false
var_dump((bool) '0');
// false
var_dump((bool) 'any other content, including FALSE');
// true

演示:https://3v4l.org/aD0QY

您可以在有关布尔值的手册中阅读更多相关信息。

字符串"FALSE"与布尔值FALSE不是一回事。

包含任何内容的字符串的计算结果为 TRUE,因此类型转换按预期工作。

您可以将字段更改为使用 INT(0 表示假,1 表示真(,在这种情况下,您可以将代码更改为:

if(!$this->config->item('mh_site_up_public')) {
show_error($this->config->item('mh_site_down_public_message'));
}

或者,如果您选择继续使用 VARCHAR,则必须将代码更改为

if($this->config->item('mh_site_up_public') === 'FALSE') {
show_error($this->config->item('mh_site_down_public_message'));
}

最新更新