php - 如果通过函数调用 PHP 代码的行为不同
问题描述
下面使用的相同代码可以正常工作,但是当您取消注释该函数并尝试调用该函数时,它的行为不一样?我正在尝试使用函数标准化 CRUD,但遇到了问题。
- print_r 在函数内部调用时不显示输出,但在函数外部调用时有效
- 通过函数调用时返回值不返回
- 我想通过函数获取返回值并决定下一步做什么。
感谢您能帮助我。谢谢
<?php
//function verifyemail($p_email) {
echo "insde function - " . $p_email;
try {
// $p_email = "r@gmail.com";
include 'db.php';
connectDB('msme_db',1) ;
$sql = "select count(*) as p_exists from msme_users where user_email = '$p_email' ;" ;
echo $sql ;
$result = $__conn->prepare($sql);
$result->execute();
$result->setFetchMode(PDO::FETCH_ASSOC);
$row = $result->fetch() ;
//print_r ($row);
if ($row)
{
$i = $row['p_exists'] ;
return $row !== false ? $row : 'x';
}
} catch (PDOException $e) {
echo " in catch" ;
die("Error occurred:" . $e->getMessage());
}
//} // End of Function
//$email = "r@gmail.com";
//echo sprintf('Email %s is %s', $mail, verifyemail($email)) ;
print_r($row) ;
?>
解决方案
我看到的问题:1.你在语句中有return
命令if
if ($row)
{
$i = $row['p_exists'] ;
return $row !== false ? $row : 'x';
}
那么你从函数中也是如此并且if
不是真的那么你不要
通过放入里面来检查它,看看你是否看到任何东西true
return
if
echo
if ($row)
{
echo 'IF Statemen in line: ' . __LINE__ . '<br>' . PHP_EOL;
$i = $row['p_exists'] ;
return $row !== false ? $row : 'x';
}
您应该重写代码,以便始终从函数返回并使用if
语句仅将值分配给$i
或$row
像这样:
function verifyemail($p_email) {
echo "insde function - " . $p_email;
try {
// $p_email = "r@gmail.com";
include 'db.php';
connectDB('msme_db',1) ;
$sql = "select count(*) as p_exists from msme_users where user_email = '$p_email' ;" ;
echo $sql ;
$result = $__conn->prepare($sql);
$result->execute();
$result->setFetchMode(PDO::FETCH_ASSOC);
$row = $result->fetch() ;
//print_r ($row);
if ($row)
{
$i = $row['p_exists'] ; //<== where do you use $i?
$row !== false ? $row : 'x';
}
} catch (PDOException $e) {
echo " in catch" ;
die("Error occurred:" . $e->getMessage());
}
return $row; //<== here you rentrun from the function
}
// End of Function
// ^ here is place for the comment, not in the line where } is
//$email = "r@gmail.com";
//echo sprintf('Email %s is %s', $mail, verifyemail($email)) ;
print_r($row) ;
?>
如果您使用没有函数体的 return 语句,那么在全局代码范围内您将结束 php 脚本执行
,因此代码print_r($row) ;
永远不会被执行
总结 - 放回声语句
echo 'line: ' . __LINE__ . '<br>' . PHP_EOL;
进入 if 语句和其他地方,并用代码检查数字,你可能会看到你没有看到你的执行流向哪里。
并将 return 语句移到语句之外if
,完全位于函数的末尾。
推荐阅读
- python - 抓取网站503错误和输出问题
- javascript - 在 Atom 上设置 p5.js
- pandas - 无法将列数据从字符串转换为数字
- ruby-on-rails - rails 6 错误消息不适用于登录/注册模式
- reactjs - 如何实现 SASS 以与原始 webpack 做出反应?
- java - 使用 JSCH 将文件从一个远程服务器发送到另一个使用 JSCH 的服务器
- python - 尝试在 Python 中关闭 Tkinter 窗口时发生 TypeError
- php - 将美分转换为美元并返回浮点值
- python-3.x - 打印总和大于或等于目标的最小子数组
- python - 如何解释热图(或一般)上的负相关?