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
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题