Php 创建2个方法或1个带参数的方法
在编写类方法以将变量设置为true/false时,最好为每个[setActiveTrue()和setActiveFalse()]编写单独的方法,还是最好使用一个接受true/false参数[setActive($x)]的方法 或 我不知道什么是“最佳实践”,但我总是采用一种方法,例如:Php 创建2个方法或1个带参数的方法,php,function,oop,functional-programming,Php,Function,Oop,Functional Programming,在编写类方法以将变量设置为true/false时,最好为每个[setActiveTrue()和setActiveFalse()]编写单独的方法,还是最好使用一个接受true/false参数[setActive($x)]的方法 或 我不知道什么是“最佳实践”,但我总是采用一种方法,例如: public function setActive ($active = true) { $this->_active = (boolean) $active; } 我可以看到争论的两面,但我的风
public function setActive ($active = true) {
$this->_active = (boolean) $active;
}
我可以看到争论的两面,但我的风格是一种方法。我会这样做
public function Active($x = true) {
$this->activeElement = $x;
}
然后您可以调用
Active()
将其设置为活动状态,调用Active(false)
将其设置为非活动状态。我希望有一个方法来设置和获取:
public function active($param='')
{switch ($param)
{case '':
return $this->active;
case true:
$this->active = true;
default:
$this->active = false;}}
$active = $this->active(); // returns active
$this->active(true); // set active to true
$this->active('true');
$this->active('false'); // those will set active to false
$this->active(false);
在这种情况下,不使用参数(或使用空字符串)调用函数会返回值,使用true调用函数会将其设置为true,使用任何其他参数调用函数会将其设置为false我不确定为什么要标记C#。在C#中使用单个属性
bool Active{get;set;}
。如果使用单个setActive()
方法,则显式地将参数强制转换为Boolean
,而不是相信它始终是一个传递给inI的布尔值,这将使方法Activate()
和Deactivate())
为了清楚地说明您实际上在做什么,我会选择setStatus($active)。如果$active为true,则您正在激活。如果不是,你是在灭活。这种事情是主观的。如果你正在寻找基于一些原则或编码实践的答案,你可能想去看看——但在发布之前一定要阅读他们的帮助中心。
public function Active($x = true) {
$this->activeElement = $x;
}
public function active($param='')
{switch ($param)
{case '':
return $this->active;
case true:
$this->active = true;
default:
$this->active = false;}}
$active = $this->active(); // returns active
$this->active(true); // set active to true
$this->active('true');
$this->active('false'); // those will set active to false
$this->active(false);