基于 PHP 中另一个变量的存在来定义一个变量的简写条件 [英] Shorthand conditional to define a variable based on the existence of another variable in PHP

查看:39
本文介绍了基于 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 总是返回 truefalse.但是,在 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 中另一个变量的存在来定义一个变量的简写条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆