首页 > 解决方案 > 如果通过函数调用 PHP 代码的行为不同

问题描述

下面使用的相同代码可以正常工作,但是当您取消注释该函数并尝试调用该函数时,它的行为不一样?我正在尝试使用函数标准化 CRUD,但遇到了问题。

  1. print_r 在函数内部调用时不显示输出,但在函数外部调用时有效
  2. 通过函数调用时返回值不返回
  3. 我想通过函数获取返回值并决定下一步做什么。

感谢您能帮助我。谢谢

<?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) ;
?>

标签: php

解决方案


我看到的问题:1.你在语句中有return命令if

if ($row)
{
    $i = $row['p_exists'] ;
    return $row !== false ? $row : 'x';
}

那么你从函数中也是如此并且if不是真的那么你不要 通过放入里面来检查它,看看你是否看到任何东西truereturnif
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) ;
?>
  1. 如果您使用没有函数体的 return 语句,那么在全局代码范围内您将结束 php 脚本执行
    ,因此代码

    print_r($row) ;
    

永远不会被执行

总结 - 放回声语句

echo 'line: ' . __LINE__ . '<br>' . PHP_EOL;

进入 if 语句和其他地方,并用代码检查数字,你可能会看到你没有看到你的执行流向哪里。
并将 return 语句移到语句之外if,完全位于函数的末尾。


推荐阅读