2014-02-28 35 views
1

如何檢查某個屬性是否存在於某個類中並使用strtolower()? (我不能使用property_exists(),因爲它不會讓我strtolower()的屬性。)我試圖使用get_object_vars()foreach()循環。查找屬性是否存在於具有strtolower的類中

error_reporting(E_ALL); 

class Test { 
    public $egg = "yay"; 
} 

$test = new Test(); 
$find = "EGG"; 
$vars = get_object_vars($test); 

foreach($vars as $var) { 
    if(strtolower($var) == strtolower($find)) 
     echo 'Var ' . strtolower($find) . ' found in Test class. Value: ' . $test->{$find}; 
    else 
     echo 'Var ' . strtolower($find) . ' not found in Test class.'; 
} 

輸出:

瓦爾雞蛋在測試類未找到。

我希望它輸出什麼:

在測試類中發現瓦爾雞蛋。價值:耶

+0

使用http://php.net/property_exists –

+0

'preg_grep(」/$ find/i「,array_keys($ vars))'? –

+0

因爲字符串可能是「蛋」而屬性可能是「蛋」。反之亦然。 – James

回答

1

您搜索的變種,而不是關鍵:

<?php 

error_reporting(E_ALL); 

class Test { 
    public $egg = "yay"; 
} 

$test = new Test(); 
$find = "EGG"; 
$vars = get_object_vars($test); 
var_dump($vars); 
foreach($vars as $key=>$var) { 
    if(strtolower($key) == strtolower($find)) 
     echo 'Var ' . strtolower($find) . ' found in Test class. Value: ' . $test->{strtolower($find)}; 
    else 
     echo 'Var ' . strtolower($find) . ' not found in Test class.'; 
} 

https://eval.in/107095

1
<?php 
    error_reporting(E_ALL); 
    class Test { 
     public $egg = "yay"; 
    } 
    $test = new Test(); 
    $find = "EGG"; 
    $vars = get_object_vars($test); 
    foreach($vars as $name => $value) { 
     if(strtolower($name) == strtolower($find)) 
      echo 'Var ' . strtolower($find) . ' found in Test class. Value: ' . $test->{strtolower($find)}; 
     else 
      echo 'Var ' . strtolower($find) . ' not found in Test class.'; 
    } 
?> 
1

接受的答案工作,如果你知道屬性始終較低的情況下,從你的問題似乎不是(或者爲什麼搜索EGG如果你已經知道它是egg)。

這將找到正確的屬性是否是大寫,小寫或混合和$find可以大寫,小寫或混合:

Class Test { 
    public $egg = "yay"; 
} 

$test = new Test(); 
$find = "EGG"; 
$vars = implode(',', array_keys(get_object_vars($test))); 

if(preg_match("/^$find$/i", $vars, $match)) { 
    $prop = $match[0]; 
    echo 'Var ' . $prop . ' found in Test class. Value: ' . $test->$prop; 
} else { 
    echo 'Var ' . $prop . ' not found in Test class.'; 
} 
+0

我的原始解決方案適用於所有情況:https://eval.in/107093 ...提問者稱它爲「小錯誤」並更新它... *聳聳肩* –

+0

因爲它返回了一個錯誤,並沒有顯示該值。我的編輯修正了... – James

相關問題