【问题标题】:Shorthand If / Else require_once PHP速记 If / Else require_once PHP
【发布时间】:2016-10-06 21:12:39
【问题描述】:

这是我的代码。它在我使用较长的 if 语句时有效,但在我使用速记时无效。对不起我的英语不好。

<?php 

function __autoload($class) {

    $path = "includes/{$class}.php";

    // IT WORKS LIKE THIS

     if (file_exists($path)) {

        require_once($path);

     }

     else {

        die("File Not Found :(");

     }

    //But Not Like This

    require_once() file_exists($path) ? $path : die("File Not Found :(");

}

?>

【问题讨论】:

  • 您不工作的替代方案不是有效的语法,只是无法工作 require_once() file_exists($path)。我强烈建议您只使用 composer 自动加载器,如果您使用任何 3rd 方代码,您可以使用任何一种方式
  • 这是一个语法错误,所以它不起作用。

标签: php if-statement require-once


【解决方案1】:

file_exists($path) ? require_once($path) : die('file not found');

但我认为,简写 if 语句适合分配变量。我会写这样的代码;

try {
    require_once($path); 
} catch (Exception $e) {
    die('file not found');
}

【讨论】:

    猜你喜欢
    • 2014-08-08
    • 2011-07-17
    • 2016-12-26
    • 2016-05-15
    • 2013-04-08
    • 1970-01-01
    • 2013-07-18
    • 2014-12-05
    • 2013-08-30
    相关资源
    最近更新 更多