Weak typing in PHP: why use isset at all?(PHP 中的弱类型:为什么要使用 isset?)
问题描述
如果我这样做,我的代码似乎可以检查是否为空
It seems like my code works to check for null if I do
if ($tx)
或
if (isset($tx))
写的比较难,我为什么要写第二个?
why would I do the second one when it's harder to write?
推荐答案
我想指出,我在这里读到的每个人的回复都应该添加一个警告:
I want to point out that everyone's reponse I've read here should have one caveat added:
"isset() 将在测试已设置为 NULL 的变量时返回 FALSE" (php.net/isset).
这意味着在某些情况下,例如检查 GET 或 POST 参数,使用 isset() 足以判断变量是否已设置(因为它要么是字符串,要么是不会被设置).但是,如果 NULL 是变量的可能值(当您进入对象和更复杂的应用程序时这种情况很常见),isset() 会让您感到无所适从.
This means that in some cases, like checking for a GET or POST parameter, using isset() is enough to tell if the variable is set (because it will either be a string, or it won't be set). However, in cases where NULL is a possible value for a variable, which is fairly common when you get into objects and more complex applications, isset() leaves you high and dry.
例如(使用 PHP 5.2.6 和 Suhosin-Patch 0.9.6.2 (cli) 测试(构建时间:2008 年 8 月 17 日 09:05:31)):
For example (tested with PHP 5.2.6 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug 17 2008 09:05:31)):
<?php
$a = '';
$b = NULL;
var_dump(isset($a));
var_dump(isset($b));
var_dump(isset($c));
输出:
bool(true)
bool(false)
bool(false)
谢谢,PHP!
这篇关于PHP 中的弱类型:为什么要使用 isset?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 中的弱类型:为什么要使用 isset?
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何替换eregi() 2022-01-01
