Shorthand conditional to define a variable based on the existence of another variable in PHP(基于 PHP 中另一个变量的存在来定义一个变量的简写条件)
问题描述
基本上,我希望能够将一个变量定义为一个事物,除非该事物不存在.我发誓在某处我看到了一个类似这样的速记条件:
Essentially, I'd love to be able to define a variable as one thing unless that thing doesn't exist. I swear that somewhere I saw a shorthand conditional that looked something like this:
$var=$_GET["var"] || "default";
但我找不到任何文档可以正确执行此操作,老实说,它可能是 JS 或 ASP 或我看到的其他东西.
But I can't find any documentation to do this right, and honestly it might have been JS or ASP or something where I saw it.
我知道上面代码中应该发生的只是检查任一语句是否返回 true.但我想我看到有人做了一些基本上定义了默认值的事情,如果第一次失败.这是任何人都知道并可以帮助我的事情吗?我疯了吗?说起来似乎是多余的:
I understand that all that should be happening in the above code is just to check if either statement returns true. But I thought I saw someone do something that essentially defined a default if the first failed. Is this something anyone knows about and can help me? Am I crazy? It just seems redundant to say:
$var=($_GET["var"]) ? $_GET["var"] : "default";
或者说特别多余:
if ($_GET["var"]) { $var=$_GET["var"]; } else { $var="default"; }
想法?
推荐答案
Matthew 已经提到了在 PHP 5.3 中实现它的唯一方法.请注意,您也可以将它们链接起来:
Matthew has already mentioned the only way to do it in PHP 5.3. Note that you can also chain them:
$a = false ?: false ?: 'A'; // 'A'
这不等于:
$a = false || false || 'A'; // true
原因是 PHP 在这方面和大多数传统语言一样.逻辑 OR 总是返回 true 或 false.但是,在 JavaScript 中,使用了最终表达式.(在一系列 OR 中,它将是第一个非假的.)
The reason why is that PHP is like most traditional languages in this aspect. The logical OR always returns true or false. However, in JavaScript, the final expression is used. (In a series of ORs, it will be the first non-false one.)
var a = false || 'A' || false; // 'A'
var b = true && 'A' && 'B'; // 'B';
这篇关于基于 PHP 中另一个变量的存在来定义一个变量的简写条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于 PHP 中另一个变量的存在来定义一个变量的简写条件
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
