2017-08-03 103 views
1

我有以下的抽象類TypesPHP檢查屬性是否存在 - 總是返回false

abstract class DocumentTypes { 
    const OPERATIONAL = 1; 
} 

這涉及到存儲在一個表中的值。該記錄必須有一個類型,這是傳遞下來的。因此,例如,如果有人正在輸入用於OPERATIONAL部件的東西,那麼這將是輸入到數據庫中的類型。

我有處理這個問題的函數:

function handle($data, $type) 
{ 
    if(!property_exists($type, DocumentTypes::class)) 
    { 
     throw new Exception("Property value must exist"); 
    } 
} 

現在什麼,我試圖做的是確保傳遞給handle的特性是抽象類Types內的財產屬性的OPERATIONAL但是存在的,當我試圖做到以下幾點:

$data = "asasfasfasfafs"; 

try { 

    handle($data, DocumentTypes::OPERATIONAL); 

}catch(Exception $e) 
{ 
    die($e); 
} 

我得到以下異常拋出:

第一個參數必須是一個對象或現有的類中

的名字,我怎麼能因此檢查值傳遞,是實際上的Types類的屬性?

回答

2

你只需要切換參數順序。類名必須是第一位的:

if(!property_exists(DocumentTypes::class $type)) 
    ... 

檢查documentation here

儘管傳遞給property_exists的第二個參數必須是一個字符串,它是您正在查找的屬性的名稱。因此,它仍然不會,如果你正在尋找1 ...工作

UPDATE 閱讀一些您的意見後,我想我明白你現在要做什麼。你想確保用戶通過一個有效的類型,而有效的類型被定義爲單獨的常量。

這是我一直解決這個問題的辦法:

abstract class DocumentTypes { 
    const OPERATIONAL = 1; 
    const OTHER_TYPE = 2; 

    public static function validTypes() 
    { 
     return [ 
      DocumentTypes::OPERATIONAL, 
      DocumentTypes::OTHER_TYPE, 
     ]; 

    } 
} 

然後你可以使用validTypes函數來驗證$type

public function handle($type) 
{ 
    if (!in_array($type, DocumentTypes::validTypes(), true)) { 
     throw new Exception("Property value must exist"); 
    } 
} 
+0

感謝您的支持。但是,我明白你從哪裏來,它總是會通過'1' ..是否有另一個我可以使用的功能? – Phorce

1

首先,一個類的屬性是不相同的類別的常數。 所以功能property_exists()不適合你。

要檢查,如果該類型(cosnstat存在),你必須使用defined()功能

中學 - 我不明白你的真正需要。你需要檢查 - 是否有一個常量定義,哪個值匹配輸入值?

如果是 - 那麼你不能這樣做。

abstract class DocumentTypes { 
    const OPERATIONAL = 1; 
} 

// -------------- 

function handle($type) { 
    if (!defined('DocumentTypes::' . $type)) { 
     throw new Exception('Property value must exist'); 
    } 
} 

// -------------- 

$data = 'asasfasfasfafs'; 
try { 
    handle($data); 
} catch(Exception $e) { 
    die($e); 
} 
+0

嗨,是的,我基本上想檢查一下,如果有人傳遞了「DocumentTypes :: OPERATIONAL」,那麼它將匹配抽象類中的一個屬性。例如,如果有人通過'DocumentTypes :: blahblah',我想拋出異常 – Phorce

+0

然後只需使用'defined('DocumentTypes :: blahblah');' – Sergej

+0

- 這就是問題所在。通過將'DocumentTypes :: OPERATIONAL'傳遞給函數,它給了我一個整數..所以在這個上定義''不會工作,因爲它正在查看值而不是名稱 – Phorce