我在一个班级中有几种方法。第一种方法是查询数据。
public function queryData() {
if ($this->result) {
return $this->result;
}
$url = 'http://domain.com/cgi-bin/cgi.exe';
$data = array('var1' => 'value1', 'var2' => 'value2');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$this->result = explode("\n",file_get_contents($url, false, $context));
array_pop($this->result);
return $this->result;
}
然后我需要将这个$ result传递给其他方法:
public function method1() {
$this->result = $this->queryData();
$data1 = explode(":",$this->result);
return $data1;
}
public function method2() {
$this->result = $this->queryData();
$data2 = explode(",",$this->result);
return $data2;
}
如果我这样做,脚本将多次查询数据。如何有效地使用一个查询然后将$ result传递给其他方法?
答案 0 :(得分:2)
将结果存储在类变量中,只有在尚未设置的情况下才执行查询。
class myClass {
private $result = null;
public function queryData() {
if ($this->result) {
return $this->result;
}
$url = 'http://domain.com/cgi-bin/cgi.exe';
$data = array('var1' => 'value1', 'var2' => 'value2');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$this0->$result = file_get_contents($url, false, $context);
return $this->$result;
}
...
}