2014-10-30 110 views
0

test.php的的if else if條件不能正常工作

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

} 
?> 

當IM執行test.php的瀏覽器輸出結果是:

file_exist 致命錯誤:不能重新聲明類表中d:線/mydomain/Slim/Lib/Table.php 2

如果語句不用於觸發class_exist。命名空間\ Slim \ Lib \ Table從不存在。

+0

也許修身框架有一個名爲「表」的類已經加載 以前檢查是否存在類比文件的存在 – 2014-10-30 22:39:41

+0

謝謝哈維爾.. – 2014-10-30 23:10:16

回答

1

class_exists的第二個可選參數是bool $autoload = true,因此它會嘗試自動加載此類。嘗試將此呼叫更改爲class_exists($value, false)請參閱manual

+0

謝謝情人..它完美.. – 2014-10-30 23:08:34

+0

不客氣! – 2014-10-30 23:09:22

1

第一,如果可以更改爲:

如果(class_exists($值)& & file_exists($文件)

其實還有其他的問題:

$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"; 
    } 
} 
+0

謝謝Miltox ..但我打算通過命名空間調用類調用或由src文件調用。再次感謝嘗試幫助我:) – 2014-10-30 23:12:29

+0

如果你想用命名空間保留它,但你必須把它放在table.php。 'namespace \ Slim \ Lib {...'這就是爲什麼沒有找到它。 – MiltoxBeyond 2014-10-30 23:15:41