类和函数内的变量范围php

时间:2015-04-16 11:58:08

标签: php 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;

时使用$p_name = 1; or $p_name = static;,问题是'receiver_name'无法获得正确的数据输入

1 个答案:

答案 0 :(得分:0)

您的类构造函数定义为此

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);