2012-12-15 31 views
1

函数Php我有这样与参数0

public function get_page($position) { 

    switch ($position) { 
     case "current": 
      echo "current"; 
      return $this->current_page; 
      break; 
     case "first": 
      echo "first"; 
      return $this->current_page >= 3 ? 1 : false; 
      break; 
     case "last": 
      echo "last"; 
      return $this->current_page <= $this->total_pages() - 2 ? ceil($this->count/$this->nb_items_to_show) : false; 
      break; 
     case "previous": 
      echo "previous"; 
      return $this->current_page - 1 >= 1 ? $this->current_page - 1 : false; 
      break; 
     case "next": 
      echo "next"; 
      return $this->current_page + 1 <= $this->total_pages() ? $this->current_page + 1 : false; 
      break; 
     case is_int($position): 
      echo "int"; 
      if ($position >= 1 && $position <= $this->total_pages()) { 
       return $position; 
      } else { 
       return false; 
      } 
      break; 
     default: 
      echo "default"; 
      return false; 
      break; 
    } 
} 

的功能。当我打电话的功能,它适用于所有的参数,除了0,然后进在开关“当前”的情况。

$paginator->get_page(0); 

如果我打电话与报价功能为 “0”,它的工作原理。 但功能可以这样调用

$paginator->get_page($paginator->get_page("current") - 2); 

我怎么能说与参数0的功能?

+0

是'$ paginator-> get_page(0);'不等同于'$分页程序 - > get_page( '第一');'? – Dale

+1

我认为某段代码丢失了......如果输入为0或“0”,switch语句应该为默认值 –

+1

参数0如何变为“current”?它不应该默认?或可能is_int()? – kennypu

回答

1

is_int回报TRUEFALSE

case is_int($position):这是一样的case -1:case 1:但不case 0:

在PHP中,TRUE被认为任何非零值

你可能寻找case intval($position):

还有一点值得注意的是,比较string0时,它总是会返回TRUE,除非字符串以数字开头,例如23balloons。这就是PHP的工作原理。

所以你要您所有的整数条件进行您的字符串条件原因如下:

当一个字符串在数值方面进行评价的结果值 和类型确定如下。

如果字符串不包含任何字符“”,‘E’,或‘E’ 和数值装配到整数类型的限制(如通过 PHP_INT_MAX定义)时,字符串将被评估为一个整数。在所有其他 的情况下,它将被评估为浮动。

该值由字符串的起始部分给出。如果字符串 以有效数字数据开头,则这将是使用的值。 否则,该值将为0(零)。有效的数字数据是一个可选符号 ,后跟一个或多个数字(可选包含小数点 ),后跟可选的指数。指数是 'e'或'E'后跟一个或多个数字。

更多信息可查询here

+1

我可能会建议对他的分页系统进行重新设计......我认为这个开关语法是有问题的 –

+1

'switch'语法没问题,它是0的字符串比较,有点误导。 – Rawkode

+0

确认。 'case intval($ position):'是要走的路。 –

-2

添加开关之前:

if (!is_string($position)) { 
goto default; 
} 
-1

变化:

is_int // Find whether the type of a variable is integer 

到:

is_numeric // Finds whether a variable is a number or a numeric string