php,开关案件返回未定义的变量
hy,
我在函数时得到了开关案例,但是当我调用它时,我会出现错误的变量,而我不知道为什么(我使用php 8)
private function getIDFromBrand() {
switch ($this->brand) {
case "Niky":
$id = 1;
break;
case "Pumo":
$id = 4;
break;
case "Coke":
if ($this->typecoke== 0) {
$id = 2;
} else {
if ($this->typecoke== 1) {
$id = 3;
}
}
break;
case "Tomato":
$id = 5;
break;
case "Riles":
$id = 6;
break;
case "TEST":
$id = 7;
break;
}
return $id; // Error Undefined variable $id
}
在我的功能顶部声明$ id时,
$ id = null
或
$ id = 0
开关未更新它,因此它将返回null或0,它将返回声明的值。
Hy,
I got switch case inside function when but when i call it, i got error Undefined Variable and i don't know why (i use PHP 8)
private function getIDFromBrand() {
switch ($this->brand) {
case "Niky":
$id = 1;
break;
case "Pumo":
$id = 4;
break;
case "Coke":
if ($this->typecoke== 0) {
$id = 2;
} else {
if ($this->typecoke== 1) {
$id = 3;
}
}
break;
case "Tomato":
$id = 5;
break;
case "Riles":
$id = 6;
break;
case "TEST":
$id = 7;
break;
}
return $id; // Error Undefined variable $id
}
When i declare $id at the top of my function, like
$id = null
or
$id = 0
The switch doesn't update it, so it will return null or 0, it will return the declared value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
您的Switch语句没有
默认
分支,因此,如果$ this-> brand
是“堆栈溢出”,则不会运行任何语句,并且代码> $ id 永远不会设置。请参阅
switch> switch> switch> switch
语句的PHP手册:同样,如果
$ this-> brand
是“可口可乐”,但是$ this- ty- typecoke
是42
,它将与该分支中的任何条件都不匹配。Your switch statement has no
default
branch, so if$this->brand
is, say, "Stack Overflow", it will not run any of the statements, and$id
will never be set.See the PHP manual for the
switch
statement:Similarly, if
$this->brand
is "Coke", but$this->typecoke
is, say,42
, it will not match either of the conditions in that branch.