如果其他条件不能正常工作


if else if condition not working properly

Test.php

<?php
$a = 'D:/mydomain/Slim/Lib/Table.php';
$b = ''Slim'Lib'Table';
foreach (array($a, $b) as $value)
{
    if (file_exists($value)) 
    {
        echo "file_exist";
        include_once($value);
        new Table();
    }
    else if (class_exists($value))
    {
        echo "class_exist";
        $class = new $value();
    } 
    else
    {
        echo "error";
    }
}
?>

和D:/mydomain/Slim/Lib/Table.php

<?php
class Table {
    function hello()
    {
        echo "test";
    }
    function justTest()
    {
        echo "just test";
    }
}
?>

当我在浏览器中执行test.php时,输出结果是:

文件已存在致命错误:无法在第2行上的D:/mydomain/Slim/Lib/Table.php中重新声明类表

class_exist的if语句不是触发器。命名空间''Slim''Lib''Table从不存在。

class_exists的第二个可选参数是bool $autoload = true,因此它尝试自动加载此类。尝试将此调用更改为class_exists( $value, false)请参阅手册。

第一个if可以更改为:

如果(!class_exists($value)&amp;file_exists($file)

实际上还有其他问题:

$a = 'D:/mydomain/Slim/Lib/Table.php';
$b = 'Table'; //Since you don't have a namespace in the Table class...
//This ensures that the class and table are a pair and not checked twice
foreach (array($a=>$b) as $file=>$value) 
{
    if (!class_exists($value) && file_exists($file)) 
    {
        echo "file_exist";
        include_once($file);
        $class = new $value();
    }
    else if (class_exists($value))
    {
        echo "class_exist";
        $class = new $value();
    } 
    else
    {
        echo "error";
    }
}