dsmvovm27249 2016-10-06 14:31
浏览 29
已采纳

PHP生成器出错

What is the best way to inform who use my generator function if something errors occurs, instead of writing weird return or raising exception like this piece of code

function csv_file_generator($csvFilename, $delimiter = ";", $enclousure = '"') {
    if(($csvHandler = fopen($csvFilename, 'rb')) === false) {
        return;
    }

    while (($row = fgetcsv($csvHandler, 0, $delimiter, $enclousure)) !== false) {
        yield $row;
    }

    if (feof($csvHandler) === false) {
        return;
    }

    if (fclose($csvHandler) === false) {
        return;
    }

    return; /* Exit Generator */
}
  • 写回答

2条回答 默认 最新

  • dongshi7433 2016-10-06 15:03
    关注
    <?php
    class CsvFileGenerator {
        protected $fp;
        protected $delimiter;
        protected $enclousure;
        public function __construct($filename, $delimiter = ";", $enclousure = '"'){
            $this->delimiter=$delimiter;
            $this->enclousure=$enclousure;
            if(!file_exists($filename)){
                throw new Exception("file [$filename] dont exists");
            }
            if(!is_readable($filename)){
                throw new Exception("file [$filename] is not readable");
            }
            $this->fp =  fopen($filename, 'rb');
            if($this->fp === false){
                throw new Exception("cant open [$filename]");
            }
        }
        public function getGenerator(){
            while (($row = fgetcsv($this->fp, 0, $this->delimiter, $this->enclousure)) !== false) {
                yield $row;
            }
        }
        public function __destruct() {
            if($this->fp){
                fclose($this->fp);
            }
        }
    }
    
    foreach( (new CsvFileGenerator('mycsvfile.csv'))->getGenerator() as $line){
        #do some
    }
    

    One way to rome. :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置