PHP 定义 var = 一个或另一个(又名:$var=($a||$b);)

PHP Define var = one or other (aka: $var=($a||$b);)

有没有办法像在 javascript 中那样将 php 变量定义为一个或另一个?

Get the size of the screen, current web page and browser window

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

我正在发送一个 post 变量,我想存储它以供以后在会话中使用。我想要完成的是将 $x 设置为 $_POST['x'] 的值,如果存在,则检查并使用 $_SESSION['x'] 如果存在,如果两者都不存在则保留 $x 未定义它们已设置;

$x = ($_POST['x'] || $_SESSION['x');

根据http://php.net/manual/en/language.operators.logical.php

$a = 0 || 'avacado'; print "A: $a\n";

will print:

A: 1

in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.

This means you can't use the '||' operator to set a default value:

$a = $fruit || 'apple';

instead, you have to use the '?:' operator:

$a = ($fruit ? $fruit : 'apple');

所以如果像这样封装 ?: 操作,我必须多做一些事情:

if($_POST['x'] || $_SESSION['x']){ 
  $x = ($_POST['x']?$_POST['x']:$_SESSION['x']);
}

或等效的也有效:

if($_POST['x']){
  $x=$_POST['x'];
}elseif($_SESSION['x']){
  $x=$_SESSION['x'];
}

我没有测试这些论文,但我认为它们也能正常工作:

$x = ($_POST['x']?$_POST['x']:
       ($_SESSION['x']?$_SESSION['x']:null)
     );

对于更多变量,我会选择一个函数(未测试):

function mvar(){
  foreach(func_get_args() as $v){
    if(isset($v)){
      return $v;
    }
  } return false;
}

$x=mvar($_POST['x'],$_SESSION['x']);

有什么简单的方法可以在 php 中实现同样的效果?

编辑澄清:如果我们想使用很多变量$x=($a||$b||$c||$d);

是的,您需要使用示例中使用的简单 ternary 运算符以及 PHP 的一些其他函数,例如 issetempty 函数PHP。所以你的变量$x会分别赋值

例子

$x = (!empty($_POST['x'])) ? $_POST['x'] : (!empty($_SESSION['x'])) ? $_SESSION['x'] : NULL;

所以上面的函数描述了如果你的 $_POST['x'] 设置的比

的值
$x = $_POST['x'];

否则它将检查 $_SESSION 的下一个值,如果它已设置,那么 $x 的值将是

$x = $_SESSION['x'];

否则最终值为

$x = null;// you can set your predefined value instead of null

$x = (!empty($a)) ? $a : (!empty($b)) ? $b : (!empty($c)) ? $c : (!empty($d)) ? $d : null;

如果你需要一个功能,那么你可以简单地实现它

$a = '';
$b = 'hello';
$c = '';
$d = 'post';

function getX(){
    $args = func_get_args();
    $counter = 1;
    return current(array_filter($args,function($c) use (&$counter){ if(!empty($c) && $counter++ == 1){return $c;} }));
}

$x = getX($a, $b, $c, $d);
echo $x;

这很简单 -

$x = (!empty($_POST['x']) ? $_POST['x'] :
          (!empty($_SESSION['x']) ? $_SESSION['x'] : null)
     );

更新

我已经成功地为您创建了一个函数,它可以完全满足您的需求,允许根据您的需求提供和获取无限的参数:

function _vars() {
    $args = func_get_args();
    // loop through until we find one that isn't empty
    foreach($args as &$item) {
        // if empty
        if(empty($item)) {
            // remove the item from the array
            unset($item);
        } else {
            // return the first found item that exists
            return $item;
        }
    }
    // return false if nothing found    
    return false;
}

要理解上面的函数,只需看上面的注释即可。

用法:

$a = _vars($_POST['x'], $_SESSION['x']);

这是你的:

Example


很简单的三元运算。您只需要先检查 post,然后再检查会话:

$a = (isset($_POST['x']) && !empty($_POST['x']) ? 
        $_POST['x']
        :
        (isset($_SESSION['x']) && !empty($_SESSION['x']) ? $_SESSION['x'] : null)
    );

一种更简单的方法是创建一个可以接受变量的函数。

 public function getFirstValid(&...$params){
    foreach($params as $param){
        if (isset($param)){
            return $param;
        }
    }
    return null;
 }

然后初始化一个变量我会做...

var $x = getFirstValid($_POST["x"],$_SESSION["y"],$_POST["z");

如果设置了 none 个变量传递,则结果将是 var x 将分配第一个设置或设置为 null 的变量。

说明:

函数 getFirstValid 接受可变数量的变量指针 (&...) 并遍历每个检查是否已设置,将返回遇到的第一个已设置的变量。

PHP7 解决方法: ?? 运算符。 $x = expr1 ?? expr2.

  • 如果 expr1 存在且不为 NULL,$x 的值为 expr1。
  • 如果expr1不存在,或者为NULL,$x的值为expr2。

https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op