PHP定义var = one或其他(又名:$ var =($ a || $ b);)

Lou*_*ier 6 php variables operators

有没有办法将php变量定义为一个或另一个就像你var x = (y||z)在javascript中一样?

获取屏幕大小,当前网页和浏览器窗口.

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

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
Run Code Online (Sandbox Code Playgroud)

我正在发送一个post变量,我想存储它以供以后在会话中使用.我想要完成的是设置$x$_POST['x'](如果存在的话)的值,然后检查并使用$_SESSION['x']它是否存在,$x如果它们都没有设置则保留undefined;

$x = ($_POST['x'] || $_SESSION['x');
Run Code Online (Sandbox Code Playgroud)

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

$ a = 0 || "阿瓦克"; 打印"A:$ a \n";

将打印:

答:1

在PHP中 - 而不是像Perl或JavaScript这样的语言打印"A:avacado".

这意味着你不能使用'||' 运算符设置默认值:

$ a = $ fruit || '苹果';

相反,你必须使用'?:'运算符:

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

所以我必须使用额外的,如果封装?:操作如下:

if($_POST['x'] || $_SESSION['x']){ 
  $x = ($_POST['x']?$_POST['x']:$_SESSION['x']);
}
Run Code Online (Sandbox Code Playgroud)

或同等的工作:

if($_POST['x']){
  $x=$_POST['x'];
}elseif($_SESSION['x']){
  $x=$_SESSION['x'];
}
Run Code Online (Sandbox Code Playgroud)

我没有测试论文,但我认为他们也会工作:

$x = ($_POST['x']?$_POST['x']:
       ($_SESSION['x']?$_SESSION['x']:null)
     );
Run Code Online (Sandbox Code Playgroud)

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

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

$x=mvar($_POST['x'],$_SESSION['x']);
Run Code Online (Sandbox Code Playgroud)

在PHP中实现相同的任何简单方法?

编辑澄清:在我们想要使用许多变量的情况下 $x=($a||$b||$c||$d);

Dar*_*ren 1

更新

我已经成功地为您创建了一个函数,它可以完全实现您想要的功能,允许根据您的需要提供和获取无限的争论:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

用法:

$a = _vars($_POST['x'], $_SESSION['x']);
Run Code Online (Sandbox Code Playgroud)

这是你的:

例子


这是一个非常简单的三元运算。您只需先检查帖子,然后检查会话:

$a = (isset($_POST['x']) && !empty($_POST['x']) ? 
        $_POST['x']
        :
        (isset($_SESSION['x']) && !empty($_SESSION['x']) ? $_SESSION['x'] : null)
    );
Run Code Online (Sandbox Code Playgroud)