简体   繁体   English

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

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

Is there a way to define a php variable to be one or the other just like you would do var x = (y||z) in javascript?有没有一种方法可以将 php 变量定义为一个或另一个,就像您在 javascript 中执行var x = (y||z)一样?

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;

i'm sending a post variable and i want to store it for a later use in a session.我正在发送一个 post 变量,我想将其存储起来以供以后在会话中使用。 What i want to accomplish is to set $x to the value of $_POST['x'] , if any exist, then check and use $_SESSION['x'] if it exist and leave $x undefined if neither of them are set;我想要完成的是将$x设置为$_POST['x']的值(如果存在),然后检查并使用$_SESSION['x']如果它存在,如果它们都不存在则保留$x未定义放;

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

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

$a = 0 || $a = 0 || 'avacado'; '鳄梨'; print "A: $a\n";打印 "A: $a\n";

will print:将打印:

A: 1答:1

in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.在 PHP 中——而不是像在 Perl 或 JavaScript 这样的语言中打印“A: avacado”。

This means you can't use the '||'这意味着您不能使用 '||' operator to set a default value:运算符设置默认值:

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

instead, you have to use the '?:' operator:相反,您必须使用 '?:' 运算符:

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

so i had to go with an extra if encapsulating the ?: operation like so:因此,如果像这样封装 ?: 操作,我必须额外使用:

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

or the equivalent also working:或等效的也有效:

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

I didn't test theses but i presume they would work as well:我没有测试这些论文,但我认为它们也会起作用:

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

for more variables i would go for a function (not tested):对于更多变量,我会选择一个函数(未经测试):

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

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

Any simple way to achieve the same in php?有什么简单的方法可以在 php 中实现相同的功能吗?

EDIT for clarification: in the case we want to use many variables $x=($a||$b||$c||$d);编辑澄清:如果我们想使用许多变量$x=($a||$b||$c||$d);

Yes you need to use simple ternary operator which you have used within your example along with some other functions of PHP like as of isset or empty functions of PHP.是的,您需要使用在示例中使用过的简单ternary运算符以及 PHP 的其他一些函数,例如isset或 PHP 的empty函数。 So your variable $x will be assigned values respectively所以你的变量$x将分别被赋值

Example例子

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

So the above function depicts that if your $_POST['x'] is set than the value of所以上面的函数描述了如果你的$_POST['x']设置为

$x = $_POST['x'];

else it'll check for the next value of $_SESSION if its set then the value of $x will be否则它会检查$_SESSION的下一个值,如果它设置了,那么$x的值将是

$x = $_SESSION['x'];

else the final value'll be否则最终值将是

$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;

If you need a function then you can simply achieve it as如果您需要一个功能,那么您可以简单地实现它

$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;

A simpler approach is to create a function that can accept variables.一种更简单的方法是创建一个可以接受变量的函数。

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

and then to initialize a variable i would do...然后初始化一个我会做的变量......

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

the result will be that the var x will be assign the first variable that is set or is set to null if none of the variables pass are set.结果将是 var x 将被分配第一个设置的变量,或者如果没有设置任何变量 pass 则设置为 null。

explanation:解释:

function getFirstValid accepts a variable number of variable pointers(&...) and loops through each checking if it is set, the first variable encountered that is set will be returned.函数 getFirstValid 接受可变数量的变量指针 (&...) 并循环检查是否已设置,遇到的第一个设置的变量将被返回。

Update更新

I've managed to create a function for you that achieves exactly what you desire, allowing infinite arguements being supplied and fetching as you desire:我已经设法为你创建了一个函数,它可以完全实现你想要的,允许无限的争论被提供和获取你想要的:

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;
}

To understand the function above, simply read the comments above.要了解上面的功能,只需阅读上面的注释。

Usage:用法:

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

And here is your:这是你的:

Example例子


It is a very simply ternary operation.这是一个非常简单的三元运算。 You simply need to check the post first and then check the session after:您只需要先检查帖子,然后检查会话:

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

PHP 7 solution: The ?? PHP 7 解决方案: ?? operator.操作员。

$x = expr1 ?? expr2
  • The value of $x is expr1 if expr1 exists, and is not NULL.如果 expr1 存在,$x 的值为 expr1,并且不为 NULL。
  • If expr1 does not exist, or is NULL, the value of $x is expr2.如果 expr1 不存在或为 NULL,则 $x 的值为 expr2。

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

It would be simple -这很简单 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM