簡體   English   中英

如果條件不正常

[英]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時,輸出結果為:

file_exist致命錯誤:無法在第2行的D:/mydomain/Slim/Lib/Table.php中重新聲明類表

如果class_exist的語句未觸發。 命名空間\\ Slim \\ Lib \\ Table不存在。

class_exists的第二個可選參數是bool $autoload = true ,因此它將嘗試自動加載此類。 嘗試將此調用更改為class_exists( $value, false)參見手冊

第一個if可以更改為:

if(!class_exists($ value)&& 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";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM