我有一个函数,接受一个checkGlossary
bool参数以及一个可选的glossary
数组。
它们的状态直接联系在一起。
如果bool值为FALSE,则不需要术语表;反之,如果bool值为TRUE,则始终需要术语表。
对我来说,这似乎可以很容易地简化为:
// Current
function doSomething($param1, $param2, $checkGlossary=FALSE, $glossary=NULL){
// blah blah blah
if($checkGlossary)
array_search($glossary[$param2]);
// etc etc etc
}
…:
// Proposed
function doSomething($param1, $param2, $glossary=FALSE){
// blah blah blah
if($glossary)
array_search($glossary[$param2]);
// etc etc etc
}
我唯一的犹豫是$glossary
的类型(bool或数组)将是不可预测的。
只要我不违反一些最佳实践指南,我就不会感到困扰。
想法吗?
使用PHP调用的mixed
数据类型的函数参数总是一个坏主意。它需要在函数中附加代码来检查参数的类型,显然这会变得非常混乱。
对于您的特殊情况,最简单的解决方案可能是使用数组长度作为是否使用术语表代码的指示器。您需要一种方法来声明不应该使用术语表数组。所以你应该问问自己:什么时候使用术语表是毫无意义的?当然是空的时候。因此,我建议您去掉标志并将array()
定义为其他参数的默认值:
function doSomething($param1, $param2, $glossary=array()) {
if (count($array) > 0) {
// do your glossary code here
}
// all the other stuff goes here
}
对我来说,这似乎在语义上是正确的,工作得很好。
我不知道你到底在那里构建什么,但另一个解决方案是将它全部放入一个类中,并将术语表作为实例变量。以防在几个函数调用中使用术语表。它大致看起来像这样:
public class SomeAccurateClassName {
private $glossary = array();
function setGlossary(array $glossary) {
$this->glossary = $glossary;
}
function doSomething($param1, $param2) {
if (count($array) > 0) {
// do your glossary code here
}
// all the other stuff goes here
}
}
考虑到你基本上有一个状态(使用或不使用术语表),它可能是一个好主意封装在一个类中
您可以使用is_array()
和is_bool()
来检查其类型!