簡體   English   中英

類和函數內部的可變范圍php

[英]Variable scope php inside class and function

我遇到的問題是,我似乎無法在類和函數中使用動態變量。

我想加載$p_name ,它從$p_real_name (數據庫條目)獲取其值,但這不起作用,即使代碼中的前兩個示例也能正常工作。

我是否缺少簡單的東西? 我試圖用幾種不同的方式進行串聯,但是實際上,我感覺自己已經超出了深度。

    $p_real_name = $row['input_1']; //This comes further up the code
    $p_name = 1; // Works fine
    $p_name = test; // Works fine
    $p_name = $p_real_name; // Does not work. 
    //If I echo out $p_real_name or even $p_name here, I get the correct value back.
    class myFunctionClass{
        private $_api_user;
        private $_api_key;
        private $_token;
        private $_test; 

        public function __construct($api_user, $api_key, $p_name){
            $this->_api_user = $api_user;
            $this->_api_key = $api_key;
            $this->_test = $p_name; 
            }
        public function login(){
            $result = $this->_make_api_call('users/login', true, array('api_user' => $this->_api_user, 'api_key' => $this->_api_key));
            $this->_token = $result['token'];
        }
        public function getToken(){
            return $this->_token;
        }
        public function myFunction($p_name) {
            $this->_test = $p_name; //tried with or without global
                $params = array(
                    'token'                 => $this->_token,
                    'receiver_name'         => $this->_test, //this only works with the first 2 examples of $p_name at the top of the code, not the 3rd example
                    'receiver_address1'     => $p_address
                );
    $ch = curl_init();      //Latest edit
    $query = http_build_query($params);

        curl_setopt($ch, CURLOPT_URL, self::API_ENDPOINT . '/' . 'shipments/imported_shipment');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $output = curl_exec ($ch);
            $http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
            curl_close ($ch);

            $output = json_decode($output, true);
        }
    }
    $testObject = new myFunctionClass($api_user, $api_key, $p_name);
    $testObject->login();
    $testObject->getToken();
    $testObject->myFunction($p_name);                       

問題是如果我使用$p_name = $p_real_name;則'receiver_name'無法獲得正確的數據輸入$p_name = $p_real_name; 僅當我使用$p_name = 1; or $p_name = static; $p_name = 1; or $p_name = static;

您的類構造函數定義為

public function __construct($api_user, $api_key, $p_name)

而你這樣稱呼它

$testObject = new myFunctionClass($api_user, $api_key);

PHP應該給您一個錯誤,因為您只傳遞了兩個變量,而不是三個。 首先做正確的事,然后我們才知道到底什么不起作用以及為什么。

它應該看起來像這樣

 $testObject = new myFunctionClass($api_user, $api_key, $p_name);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM