dongluan2612 2017-01-23 18: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-23 18: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
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?