PHP对象和方法-Dos$object->;方法请求数据或仅存储数据
我有一个查询,它请求数据并返回一个名为$result的数组PHP对象和方法-Dos$object->;方法请求数据或仅存储数据,php,class,oop,object,Php,Class,Oop,Object,我有一个查询,它请求数据并返回一个名为$result的数组 class data { public function __construct ($type) { $this->type = $type; } function set_url($url) { // Construct URL based on type. return $this->url; } fu
class data {
public function __construct ($type) {
$this->type = $type;
}
function set_url($url) {
// Construct URL based on type.
return $this->url;
}
function curl_data($url) {
$url = $this->set_url(); //Run the set_url function to work out the url of the object
$options = array (CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => etc ); // stop after 10 redirects
//Initiatiate the connection
$ch = curl_init ( $url );
curl_setopt_array ( $ch, $options );
//Capture the content
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
$header ['content'] = $content;
return $header ['content'];
}
}
然后,我可以使用以下方法调用此数据:
$object = new data('type1');
$object->curl_data(); //Select the URL, Process the api call, return the content
到目前为止一切正常。然而,当我在数据类中使用类似的函数解码json时,我遇到了一个错误,因为我从服务器请求了太多的数据
public function decode_json($response){
//$this->curl_data();
//manipulate the response
$response = json_encode($response,true);
$response = json_decode($response);
return $response;
}
我认为这是因为我的decode函数执行了一个newcurl\u data()调用,而不仅仅是使用已经检索到的数据。我尝试过使用以下两种方法调用decode函数,但不确定是哪种方法破坏了它/如何使它工作
$object->decode_json($object->curl_data()); //with $decode_json escaping $this->curl_data(); and requesting ($response)
$object->decode_json(); //with decode_json() using $this->curl_data(); and not requiring ($response)
我的问题是-我的$object->curl_data()如何处理;查询实际上是有效的,我如何通过引用它来避免将查询相乘,从而从服务器重新请求数据。这在JSON查询中很常见,但如果在从自己的数据库等进行请求时出错,则可能会导致严重的性能问题
“->”语法似乎会通过该方法产生额外的查询,而不仅仅是存储数据,但如果我只是将数据存储在变量中,我就不会按照OOP原则进行编码。也许这就是您想要的:
$result1 = $object->curl_data();
$result2 = $object->decode_json($result1);
$result3 = $object->calculate_figures($result1);
只执行一次curl\u数据,并使用两种不同的方法处理结果。是否编写了函数
curl\u data()
?是的。抱歉,刚才在帖子里说得更清楚了。对于如何避免引用$object->decode_json(),我感到困惑;这将取决于curl_data();从两次请求数据开始-每次一次。好的,那么你不明白它是如何工作的?它打开一个连接,获取数据,关闭连接,然后返回数据。我明白这一点——我不知道如何更改$object->decode_json($object->curl_data());只需调用一次“decode_json()”;有curl_data()的;在它内部,无需通过请求多组数据来重载服务器。特别是,因为我只想执行curl_data()函数一次,但我可能想在以后对数据做很多事情——并冒着调用decode_json函数或其他多次依赖于它的函数的风险……请您也添加错误,好吗?