昨天的面试题中,有一题栈的应用,当时知道原理,代码具体没写过,今天就来写写。。
<?php /* * Created on 2015-4-9 * * PHP栈的应用 */ class Stack{ private $stack_arr =array(); private $end = null; public function push($str){ if($this->end === null){ $this->end = 0; }else{ $this->end++; } $this->stack_arr[$this->end] = $str; } public function pop(){ // if($this->end=null){return false;} //如果这样写,变量end为0的时候,是否就出错了 if(empty($this->stack_arr)){return false;} $pop_data = $this->stack_arr[$this->end]; array_splice($this->stack_arr,$this->end); $this->end--; return $pop_data; } public function getData(){ return $this->stack_arr; } } $arr = array(); $data_obj =new Stack(); $data_obj->push("1_one"); $data_obj->push("2_two"); $data_obj->push("3_three"); $data_obj->pop(); $arr = $data_obj->getData(); print_r($arr); ?>
打印结果:
---------------------------------------------------------------------------------------------------------------
Array ( [0] => 1_one [1] => 2_two )
以上就介绍了PHP栈的写法,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。