我试图在codeigniter中传递一个参数。
这对我有用:
function the_kwarg($gender){
$gender = $this->uri->segment(3);
}
但是,我不明白为什么这是错误的
function the_kwarg($gender=$this->uri->segment(3)){
//$gender = $this->uri->segment(3);
}
为什么这样做是错误的?
我试图在codeigniter中传递一个参数。
这对我有用:
function the_kwarg($gender){
$gender = $this->uri->segment(3);
}
但是,我不明白为什么这是错误的
function the_kwarg($gender=$this->uri->segment(3)){
//$gender = $this->uri->segment(3);
}
为什么这样做是错误的?
因为函数只能接受标量默认值,所以它不能$this
在该上下文中评估(或任何变量)。
从手册:
函数可以为标量参数定义 C++ 风格的默认值。
和:
默认值必须是常量表达式,而不是(例如)变量、类成员或函数调用。
函数参数默认值不能是动态表达式,例如
function foo ($x = 1 + 1) { }
是非法的,因为1 + 1
是一个表达式。我们都知道结果是一个常量2
,但是 PHP 并不聪明,只看到一个表达式。
虽然人们已经给了你正确的答案,但我可以给你一个如何解决问题的例子:
function the_kwarg($gender = null){
$gender = (!is_null($gender)) ? $gender : $this->uri->segment(3);
}
你为什么不只使用像这样的功能
function the_kwarg($gender){
echo $gender; // will echo male
}
// http://www.example.com/controller/the_kwarg/male
在 CI 中uri segments
,函数名后面基本上是函数的参数