【发布时间】:2015-10-31 12:32:33
【问题描述】:
我正在编写一个大型项目,这里有一个我会经常使用的类:
class Star
{
/**
* Add
*
* Add a star to something.
*
* @param int $ID The ID of the thing.
*/
function Add($ID)
{
if($this->Starred($ID))
return 'You starred it already.';
if(!$this->Existing($ID))
return 'The one you tried to star does no longer exist.';
$this->DB->Star($ID);
return 'Starred successfully!';
}
}
$Star = new Star();
但我会以不同的方式使用它,例如:单页或函数内部,
这就是问题所在,有时,我想知道返回码而不是消息,
但是当我在单页中使用它时,我希望它返回消息,
所以如果我将Add() 函数更改为:
function Add($ID)
{
if($this->Starred($ID))
return 0;
if(!$this->Existing($ID))
return 1;
$this->DB->Star($ID);
return 2;
}
我现在可以在我的函数中使用它来处理错误:
/** Leaves a comment */
$Comment->Say('Hello.', $ID);
/** Auto star the post because we commented on it */
if($Star->Add($ID) == 2)
{
/** Remove the comment because the post does no longer exist */
$Comment->Remove('Hello.', $ID);
return 'Sorry ; _ ;, the post does no longer exist.';
}
但是如果我需要在许多其他页面中返回消息怎么办?
我每次都需要写这段代码吗?
switch($Star->Add($ID))
{
case 0:
return 'You starred it already.';
break;
case 1:
return 'The one you tried to star does no longer exist.';
break;
case 2:
return 'Starred successfully!';
break;
}
我只是对此感到困惑,任何帮助将不胜感激。
【问题讨论】:
-
再添加两个函数
getCode()和getMessage()。将代码和消息分配给私有变量。让getCode()返回code,和message一样。