作为PHP类的新手,我试图找出从文本文件(电子邮件)中检索值的最佳方法。文本文件逐行转换为数组。我一次处理多个文本文件。从一些文本文件中我需要检索比其他文件更多的信息,所以我创建了一个包含我需要的所有函数的类。这是(简而言之)我想出的:
<?php
$to_process = array(
'9/24/15 11:03:04 PM Task Start',
'[...]',
'[...]',
'9/24/15 11:25:54 PM Task Stop',
' ',
' '
);
$message = new process;
$start = $message->retrieve_start(to_process);
$stop = $message->retrieve_stop(to_process);
class process {
function retrieve_start($arr) {
$start = explode(" ", $arr[0]);
return $this->$start[1];
}
function retrieve_other($arr) {
// do stuff
}
function retrieve_stop($arr) {
// do other stuff
}
}
?>
它完成了这项工作,但每次调用其中一个函数时,数组都会传递给函数。这对我来说效率不高。我怎样才能提高效率呢?
答案 0 :(得分:1)
您可以使用构造函数方法将进程数组加载到对象中,就像这样
<?php
class process {
protected $to_process = array();
public function __construct($theProcessArray)
{
$this->to_process = $theProcessArray;
}
public function retrieve_start()
{
$start = explode(" ", $this->to_process[0]);
return $start[1];
}
public function retrieve_other()
{
// do stuff
}
public function retrieve_stop()
{
// do other stuff
}
}
$to_process = array('9/24/15 11:03:04 PM Task Start',
'[...]', '[...]',
'9/24/15 11:25:54 PM Task Stop',
' ', ' ');
$message = new process($to_process);
$start = $message->retrieve_start($to_process);
$stop = $message->retrieve_stop($to_process);
?>