【问题标题】:PHP Alternative to if (!isset(...)) {...} => GetVar($Variable, $ValueIfNotExists)PHP 替代 if (!isset(...)) {...} => GetVar($Variable, $ValueIfNotExists)
【发布时间】:2018-09-07 22:35:12
【问题描述】:

当我在 PHP 中使用不存在变量时,我会收到警告/错误消息。

注意:未定义的变量


所以通常我会先写一个 if 语句来初始化它。

示例 1:

if (!isset($MySpecialVariable))
{
  $MySpecialVariable = 0;
}
$MySpecialVariable++;

示例 2:

if (!isset($MyArray["MySpecialIndex"]))
{
  $MyArray["MySpecialIndex"] = "InitialValue";
}
$Value = $MyArray["MySpecialIndex"];

缺点是要写$MySpecialVariable$MyArray["MySpecialIndex"]好几次,程序会臃肿。

如何通过仅一次编写变量来获得相同的结果?

我正在寻找类似的东西

GetVar($MySpecialVariable, 0); # Sets MySpecialVariable to 0 only if not isset()
$MySpecialVariable++;

$Value = GetVar($MyArray["MySpecialIndex"], "InitialValue");

【问题讨论】:

    标签: php variables exists isset


    【解决方案1】:

    当您运行 PHP7 时,您可以使用 null coalescing operator
    喜欢:

    $myVar = $myVar ?? 0;
    

    【讨论】:

      【解决方案2】:
      function GetVar(&$MyVar, $ValueIfVarIsNotSet)
      {
          $MyVar = (isset($MyVar)) ? $MyVar : $ValueIfVarIsNotSet;
          return $MyVar;
      }
      

      关键是通过引用(&$MyVar)传递请求的变量。否则,不可能调用带有可能未初始化变量的函数。

      测试代码:

      echo "<pre>";
      
      unset($a);
      $b = "ValueForB";
      unset($c);
      $d = "ValueForD";
      
      echo (isset($a)) ? "a exists" : "a NotSet";
      $a = GetVar($a, 7); # $a can be passed even if it is not set here
      $a++;
      echo "\nValue=$a\n";
      echo (isset($a)) ? "a exists" : "a NotSet";
      echo "\n\n";
      
      echo (isset($b)) ? "b exists" : "b NotSet";
      echo "\nValue=".GetVar($b, "StandardValue2")."\n";
      echo (isset($b)) ? "b exists" : "b NotSet";
      echo "\n\n";
      
      echo (isset($c)) ? "c exists" : "c NotSet";
      echo "\nValue=".GetVar($c, "StandardValue3")."\n";
      echo (isset($a)) ? "c exists" : "c NotSet";
      echo "\n\n";
      
      echo (isset($d)) ? "d exists" : "d NotSet";
      echo "\nValue=".GetVar($d, "StandardValue4")."\n";
      echo (isset($d)) ? "d exists" : "d NotSet";
      echo "\n\n";
      
      echo "</pre>";
      

      输出:

      一个未设置
      值=8
      存在

      b 存在
      Value=ValueForB
      b 存在

      c 未设置
      值=标准值3
      c 存在

      d 存在
      Value=ValueForD
      d 存在

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-13
        • 2013-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多