dongluan2612 2017-01-24 02:48
浏览 38
已采纳

无法使用另一个函数内的函数声明的变量

Didn't know how to ask this question.

I was working on setting up class to handle my Database interaction and have a weird interaction of passing variables. I must be missing something.

I have a class DataBaseAPI I have a function QueryDB($value) that will be called by other functions. But it has an issue with my declaring that $value inside another function. Example:

Works

include_once('DataBaseAPI.php');
$DB = new DataBaseAPI();

$test = $DB->QueryDB('id');
echo $test;

Doesn't Work

include_once('DataBaseAPI.php');
$DB = new DataBaseAPI();

$test = $DB->getId();
echo $test;

Start of the class in DataBaseAPI.php

class DataBaseAPI {


  public function getId(){
    //the same function defined the same way but needing to use $this
    $this->QueryDB('id');//seems like a waste here but is for ease of use later on
  }


  public function QueryDB($value){
    echo $value; //echo's id
    global $conn; 
    $token = '7ci4f8ykfik3ndzufksy1dp16x3na4'; //Test Token not a real token
    $doesExists = "SELECT $value FROM user_info WHERE token='$token'";
    $existsResult = mysqli_query($conn, $doesExists);
    $check = $existsResult->fetch_assoc();
    return $check[$value];
  }
} 

I even checked with an echo the $value in the QueryDB($value) echo's id the same way as when I call the function directly.

I just don't understand why the first method works yet the second method doesn't, yet I'm still calling it the same way. Just inside another function.

  • 写回答

1条回答 默认 最新

  • dongmingxiang0312 2017-01-24 02:50
    关注

    Return the result of getId() in order to store in your $test. Do

     public function getId(){
        return $this->QueryDB('id');//seems like a waste here but is for ease of use later on
      }
    

    instead of

     public function getId(){
        $this->QueryDB('id');//seems like a waste here but is for ease of use later on
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器