[英]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.