尝试访问数据时变量不起作用

时间:2014-10-29 00:41:28

标签: php

我想设置我的类变量不在__construct中,而是在__construct调用的方法中。我不确定我是否正确行事。

class request{
private $sNote;
private $iAffectedUserId;
private $iUserId;
private $sPassword;
private $sFirstName;
private $sLastName;

public function __construct($sService, $oData, $iAffectedUserId){
    $this->iUserId = $_SESSION['user_Id'];
    $this->sPassword = $_SESSION['password'];
    $this->sFirstName = $_SESSION['firstName'];
    $this->sLastName = $_SESSION['lastName'];
    switch($sService){
        case 'note':
            $this->requestNote();
            break;
        default:
            echo "ErrorCode: 4000";
            break;
    }
}

public function requestNote(){
    $sQuery = "SELECT * FROM `note` WHERE `sender_Id` = '" . $this->iUserId . "'";
    echo $sQuery;
    $oResult = conn($sQuery);
    if(!is_array($oResult)||!isset($oResult)||empty($oResult)||is_null($oResult)){
        echo "ErrorCode: 5000";
    } else{
        //echo $this->iUserId;
        echo json_encode($oResult);
    }
}
}

此代码的结果为$sQuery留下了$this->iUserId所在的空白值。这意味着什么都没有。

编写其他代码的方法。

class request{
private $sNote;
private $iAffectedUserId;
private $iUserId;
private $sPassword;
private $sFirstName;
private $sLastName;

public function __construct($sService, $oData, $iAffectedUserId){
    $this->init_Session_Variables();
    switch($sService){
        case 'note':
            $this->requestNote();
            break;
        default:
            echo "ErrorCode: 4000";
            break;
    }
}

private function init_Session_Variables(){
    $this->iUserId = $_SESSION['user_Id'];
    $this->sPassword = $_SESSION['password'];
    $this->sFirstName = $_SESSION['firstName'];
    $this->sLastName = $_SESSION['lastName'];
}

public function requestNote(){
    $sQuery = "SELECT * FROM `note` WHERE `sender_Id` = '" . $this->$iUserId . "'";
    echo $sQuery;
    $oResult = conn($sQuery);
    if(!is_array($oResult)||!isset($oResult)||empty($oResult)||is_null($oResult)){
        echo "ErrorCode: 5000";
    } else{
        //echo $this->iUserId;
        echo json_encode($oResult);
    }
}
}

这种方式给我一个错误说:

注意 C中的未定义变量:iUserId: C:\ xampp \ htdocs \ apps \ MyVyn \ Utils \ utils \ php \ userQuery.php

我真的很茫然。什么在爆炸?

1 个答案:

答案 0 :(得分:2)

你在iUserID前面有一个额外的$

 $sQuery = "SELECT * FROM `note` WHERE `sender_Id` = '" . $this->$iUserId . "'";

应该是

 $sQuery = "SELECT * FROM `note` WHERE `sender_Id` = '" . $this->iUserId . "'";