在这个示例代码中,我在所有函数中运行通配符搜索。函数basic()可能会给出正确的答案,而另一个函数错误的答案,反之亦然。
一旦得到正确答案,如何抑制一个函数的失败部分关于另一个功能?也就是说,如果我已经展示了"这是一种碱金属",我不想展示"金属是未知的"。
<?php
class metals
{
function alkali()
{
if (($rowC['description'] == " Alkali Metal")) {
echo '';
} else {
echo 'metal is unknown';
}
}
function alkaline_earth()
{
if (($rowC['description'] == " Alkali earth Metal")) {
echo ' this is an alkali earth metal';
} else {
echo 'metal is unknown';
}
}
//end of class
}
// create an object for class name
$abc = new metals();
$abcd = new metals();
// call the functions in the class
$abc->alkali();
$abcd->alkaline_earth();
?>
实现所需结果的一种更短、更优雅的方法是:
<?php
class metals {
// Consider defining this as a static function if $rowC is not
// intended to be a member of the class `metals`.
function isMatch($search) {
return $rowC['description'] == $search;
}
}
$abc = new metals();
$searches = array('Alkali Metal', 'Alkali Earth Metal', 'Some Other Metal');
foreach ($searches as $search) {
if ($abc->isMatch($search)) {
echo 'Match found: ' . $search;
break;
}
}
?>
循环将输出第一个匹配项,然后退出。