Невозможно прочитать защищенное значение экземпляра объекта - PullRequest
2 голосов
/ 06 июня 2019

Я пытаюсь разделить роль в концепции ОО, я создал родительский класс, дочерний класс и создал экземпляр класса на начальной странице.

Но var_dump($this->process_result_sets); ничего не вернуть, кто-нибудь может объяснить, почему?

mail.php

//header('Content-type: application/json');
require_once("../core/core.connection.manager.php");

$responseObj = new ResponseManager();

$json_string = null;

try{
    $mssql_instance = new MSSQLManager();
    $responseObj->AddResultSets($mssql_instance->GetResultSets());


    $json_string = $responseObj->GetJSON();

}catch(Exception $e){
}

core.connection.manager.php

require_once(dirname(__FILE__)."/../config/config.php");
require_once(dirname(__FILE__)."/core.manager.loader.php");

class ResponseManager{
    protected $message_list;
    protected $error_message_list;
    protected $overall_status;
    protected $process_result_sets;

    function __construct(){
        $this->message_list = array();
        $this->error_message_list = array();
        $this->overall_status = "";
        $this->process_result_sets = array();
    }

    public function AddResultSet($resultSet){
        if(empty($resultSet))
            return false;

        if(isset($resultSet->message) && !empty($resultSet->message))
            array_push($this->message_list, $resultSet->message);

        if(isset($resultSet->error_message) && !empty($resultSet->error_message))
            array_push($this->error_message_list, $resultSet->error_message); 

        array_push($this->process_result_sets, $resultSet);

        print_r($this);
        print_r("<hr>");

        return true;
    }
    public function AddResultSets($resultSets){
        return array_merge($this->process_result_sets, $resultSets);
    }
    public function GetResultSets(){
        print_r($this->process_result_sets);
        print_r("<hr>");
        return $this->process_result_sets;
    }
    public function AddMessage($message){
        array_push($this->message_list, $message);
    }
    public function AddErrorMessage($err_msg){
        array_push($this->error_message_list, $err_msg);
    }

    public function Get(){
        return $this->getJSON();
    }
    public function GetJSON(){
        var_dump($this->process_result_sets);
    }
}

class ResultSet{
    public $message;
    public $error_message;
    public $status;
    public $data;
    public $num_rows;
}

db.manager.php

class DatabaseManager{
    private $hostname_fyp;
    private $database_fyp;
    private $username_fyp;
    private $password_fyp;

    public $responseObj;

    function __construct(){
        $this->responseObj = new ResponseManager();

        try {
            $this->hostname_fyp = _DB_HOST;
            $this->database_fyp = _DB_NAME;
            $this->username_fyp = _DB_USER;
            $this->password_fyp = _DB_PASS;

            $hostname_fyp = $this->hostname_fyp;
            $database_fyp = $this->database_fyp;
            $username_fyp = $this->username_fyp;
            $password_fyp = $this->password_fyp;

            //$this->responseObj->AddResultSet((object) array('message' => 'DatabaseManager __construct.'));
        }catch (Exception $e) {
            //$this->responseObj->AddResultSet((object) array('error_message' => $e->getMessage()));
        }catch (PDOException $e) {
            //$this->responseObj->AddResultSet((object) array('error_message' => $e->getMessage()));
        }
        $this->_Initialize();
    }

    function _Initialize(){
        //$this->responseObj->AddResultSet((object) array('message' => 'Initialized in DatabaseManager()'));
        $this->Initialize();
    }

    function Initialize(){  }

    function GetResultSets(){
        return $this->responseObj->GetResultSets();
    }

    function CloseConnection(){
        //$this->responseObj->AddResultSet((object) array('message' => 'close db connection.'));
    }

    function __destruct() {
        $this->CloseConnection();
    }
}

db.mssql.manager.php


class MSSQLManager extends DatabaseManager {

    function __construct(){
        parent::__construct();

        $resultSet = new ResultSet();
        $resultSet->message = "MSSQLManager __construct.";
        $this->responseObj->AddResultSet($resultSet);
    }
    function Initialize(){
        //$this->responseObj->AddResultSet((object) array('message' => 'Initialized in MSSQLManager()'));
    }
    function CloseConnection(){
        //$this->responseObj->AddResultSet((object) array('message' => 'close mssql connection.'));
    }
}

ожидаемый результат - «MSSQLManager __construct». сообщение. в результате сообщение потеряно при 3-м вызове.

//add value from child class
ResponseManager Object ( [message_list:protected] => Array ( [0] => MSSQLManager __construct. ) [error_message_list:protected] => Array ( ) [overall_status:protected] => [process_result_sets:protected] => Array ( [0] => ResultSet Object ( [message] => MSSQLManager __construct. [error_message] => [status] => [data] => [num_rows] => ) ) ) 

//get value from parent class
Array ( [0] => ResultSet Object ( [message] => MSSQLManager __construct. [error_message] => [status] => [data] => [num_rows] => ) ) 

//get value by object instance
array(0) { } 

1 Ответ

0 голосов
/ 19 июня 2019

Наконец, я обнаружил ошибку: ошибка, вызванная array_merge, просто возвращает объединенный результат, и он не обновит объединенный результат до параметра.

код изменился, как показано ниже:

core.connection.manager.php

require_once(dirname(__FILE__)."/../config/config.php");
require_once(dirname(__FILE__)."/core.manager.loader.php");

class ResponseManager{
    protected $user_message_list;
    protected $log_message_list;
    protected $error_message_list;
    protected $overall_status;
    protected $process_result_sets;
    public $dataSets;
    private $_data_set_count;

    function __construct(){
        $this->user_message_list = array();
        $this->log_message_list = array();
        $this->error_message_list = array();
        $this->overall_status = "empty";
        $this->process_result_sets = array();
        $this->dataSets = array();

        $this->_data_set_count=0;
    }

    public function AddResultSet($resultSet, $tableName=""){
        if(empty($resultSet))
            return false;

        $this->AddUserMsg($resultSet->GetUserMsg());
        $this->AddLogMsg($resultSet->GetLogMsg());
        $this->AddErrorMsg($resultSet->GetErrorMsg());

        if(count($resultSet->data_set)>0){
            $this->_data_set_count++;
            $this->dataSets[$this->_data_set_count-1] = $resultSet->data_set;
            if(!empty($tableName)){
                $this->dataSets[$tableName] = $resultSet->data_set;
            }
        }

        array_push($this->process_result_sets, $resultSet);

        return true;
    }
    public function AddResultSets($resultSets){
        $this->process_result_sets = array_merge($this->process_result_sets, $resultSets);
        return $this->process_result_sets;
    }

    public function AddUserMsg($user_msg){
        if(!empty($user_msg))
            array_push($this->user_message_list, $user_msg);
    }

    public function AddLogMsg($log_msg){
        if(!empty($log_msg))
            array_push($this->log_message_list, $log_msg);
    }

    public function AddErrorMsg($err_msg){
        if(!empty($err_msg)){
            array_push($this->error_message_list, $err_msg);
            $this->overall_status = "error";
        }
    }

    public function GetUserMsg(){
        return $this->user_message_list;
    }

    public function GetLogMsg(){
        return $this->log_message_list;
    }

    public function GetErrorMsg(){
        return $this->error_message_list;
    }

    /*
    public function AddMessage($message){
        array_push($this->user_message_list, $message);
    }
    public function AddErrorMessage($err_msg){
        $this->error_message_list = array_push($this->error_message_list, $err_msg);
        return $this->error_message_list;
    }
    */

    protected function CheckOverallStatus(){
        if(count($this->GetErrorMsg())>0){
            $this->overall_status = "error";
        }else{
            $this->overall_status = "success";
        }
    }

    public function Get(){
        $this->CheckOverallStatus();
        return get_object_vars($this);
    }
    public function GetJSON(){
        return json_encode($this->Get());
    }
}

class ResultSet{
    public $user_message;
    public $log_message;
    public $error_message;
    public $exceptionObj;
    public $status;
    public $num_rows; // the number of rows in a result set
    public $affected_rows; // the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    public $inserted_id;
    public $data_set;

    function __construct($msg="", $err_msg=""){
        $this->user_message = $msg;
        $this->user_message = "";
        $this->error_message = $err_msg;
        $this->exceptionObj = array();
        $this->status = "empty";
        $this->data_set = array();
        $this->num_rows = -1;
        $this->affected_rows = -1;
        $this->inserted_id = -1;
    }

    function SetUserMsg($msg=""){
        $this->user_message = $msg;
    }
    function SetLogMsg($msg=""){
        $this->log_message = $msg;
    }
    function SetErrorMsg($msg=""){
        if(!empty($msg)){
            $this->error_message = $msg;
            $this->SetStatusError();
        }
    }
    function SetErrorObj($err_obj){
        $this->exceptionObj = (array)$err_obj;
    }

    function GetUserMsg(){
        return $this->user_message;
    }
    function GetLogMsg(){
        return $this->log_message;
    }
    function GetErrorMsg(){
        return $this->error_message;
    }
    function GetErrorObj(){
        return $this->exceptionObj;
    }

    function SetStatusError(){
        $this->status = "error";
    }
    function SetStatusSuccess(){
        $this->status = "success";
    }
}

// catch warning and convert to exception
// /1211402/mogu-li-ya-poprobovat-poimat-preduprezhdenie
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    // error was suppressed with the @-operator
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...