一直想成为一个文笔高超的写手,却一不小心成了码农。不知道,你有没有看原作者的一些观点(传送门)。我们为什么要学习新知识,又应该如何学习新知识。我看过很多书,但我记得的不多。有时候觉得自己像条鱼,真的只有七秒的记忆。正如原作者所说,学习知识最好的方法就是实践。只有这样才能掌握知识。之前,我看了一篇关于PHPPHP的新闻文章。不知道还有没有人记得这个项目。当时出现的时候,我想很多人都说这个无聊的项目没有用户。后来才渐渐发现自己的无知。PHPPHP虽然没有像pypy那样发展,但是给了很多想学习解释器的同学一个学习和实践的途径。言归正传,这一段的解释器已经可以完成计算器的很多功能,可以实现多位数的连续加减法。Talkischeap,showmethecode.type=$type;$this->value=$value;}/**使用这个方法获取类的私有属性*/publicfunction__get($name){return$this->{$name};}/**用于调试*/publicfunction__toString(){return'type:'.$this->type.'值:'.$this->value;}}//解释器类Interpreter{private$current_char;私人$current_token;私人$文本;私人$pos=0;/***$text需要解释的字符串*/publicfunction__construct($text){//去掉这些空格前后可能存在的空格$this->text=trim($text);//初始化获取第一个字符$this->current_char=$this->text[$this->pos];}publicfunctionerror(){thrownew\Exception('Lexererosion');}/*步进法,每操作一位就前进一步*/publicfunctionadvance(){$this->pos++;如果($this->pos>strlen($this->text)-1){$this->current_char=null;}else{$this->current_char=$this->text[$this->pos];}}/*删除空格*/publicfunctionskip_whitespace(){if($this->current_char!=null&&$this->current_char==WHITESPACE){$this->advance();}}/*如果要支持多位整数,需要存储每一位数字*/publicfunctionintegers(){$result='';//用于存储数字while($this->current_char!=null&&is_numeric($this->current_char)){//只要当前字符是数字,就会一直循环,把数字存入$result$result.=$this->current_char;$this->advance();//步进方式,每次字符运算后前进一位}returnintval($result);//将数字串转为整数}//获取当前字符的Tokenpublicfunctionget_next_token(){while($this->current_char!=null){if($this->current_char==WHITESPACE){$this->skip_whitespace();继续;}if(is_numeric($this->current_char)){returnnewToken(ISINTEGER,$this->integers());}如果($this->current_char=="+"){$this->advance();返回新令牌(加号,'+');}if($this->current_char=="-"){$this->advance();返回新令牌(负号,'-');}returnnewToken('EOF',null);}}//如果字符类型与判断的类型相同,则继续,否则输入错误publicfunctioneat($token_type){if($this->current_token->type==$token_type){$this->current_token=$this->get_next_token();}else{$this->error();}}publicfunctionterm(){$token=$this->current_token;$this->eat(ISINTEGER);返回$令牌->值;}//解释方法publicfunctionexpr(){$this->current_token=$this->get_next_token();//获取字符串开头部分的数字$result=$this->term();while($this->current_token->type==PLUS||$this->current_token->type==MINUS){$token=$this->current_token;如果($token->type==PLUS){$this->eat(PLUS);$result=$result+$this->term();}elseif($token->type==MINUS){$this->eat(MINUS);$result=$result-$this->term();}}返回$结果;}}do{fwrite(STDOUT,'xav>');;$输入=fgets(标准输入);$Interpreter=新解释器($input);echo$Interpreter->expr();未设置($国米更优);}而(真);
