Home > Backend Development > PHP Tutorial > 帮忙看下怎么会返回null

帮忙看下怎么会返回null

WBOY
Release: 2016-06-23 14:13:21
Original
1130 people have browsed it

本帖最后由 snowlove 于 2013-06-17 18:27:34 编辑

<?phpfunction newtripos($str,$findstr,$count,$off=0){	$pos=stripos($str,$findstr,$off);	$count--;	if($count>0 && $pos!=false){		$pos=newtripos($str,$findstr,$count,$pos+1);	}else{		var_dump($pos);		return $pos;	}}$a="456123456455654466";$b=newtripos($a,'6',4);var_dump($b);?>	
Copy after login


执行后显示$b是null。而在函数返回前,执行的var_dump($pos),显示是int(16)。
为什么var_dump($b)会是null?


回复讨论(解决方案)

你使用了递归,return $pos; 在进入递归后会作用于 $pos=newtripos($str,$findstr,$count,$pos+1);
而你并没有在这个分支里对 $pos 作处理(也就是将结果返回到上一级递归)
我说的可能连我自己都不好理解,看代码:

function newtripos($str,$findstr,$count,$off=0){    $pos=stripos($str,$findstr,$off);    $count--;    if($count>0 && $pos!=false){        $pos=newtripos($str,$findstr,$count,$pos+1);    }    return $pos;}
Copy after login

你的代码没问题。
function newtripos($str,$findstr,$count,$off=0){
$pos=stripos($str,$findstr,$off);
$count--;
if($count>0 && $pos!=false){
$pos=newtripos($str,$findstr,$count,$pos+1);
}else{
var_dump($pos);//程序执行到这里可以正确的打出$pos的值。继续执行就应该结束函数,返回$pos
return $pos; //这里就应该返回$pos的值了。
}
}
$a="456123456455654466";
$b=newtripos($a,'6',4); //可是这里$b 怎么没接收到$pos,是个null
var_dump($b);
?>

把else体去掉,和没去掉有这么大差别?

差别大多了,因为没有去掉else时,相当于

<?php	if($count>0 && $pos!=false){		$pos=newtripos($str,$findstr,$count,$pos+1);                return null;	}else{		var_dump($pos);		return $pos;	}}?>	
Copy after login


而去掉else以后,则是

<?php	if($count>0 && $pos!=false){		$pos=newtripos($str,$findstr,$count,$pos+1);                return $pos;	}else{		var_dump($pos);		return $pos;	}}?>	
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template