Home > Article > Backend Development > How to write PHP stack
Among the interview questions yesterday, there was a question about the application of stack. I knew the principle at that time, but I had not written the specific code. I will write about it today. .
<?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); ?>
Print results:
---------------------------------------- -------------------------------------------------- ---------------------
Array ( [0] => 1_one [1] => 2_two )
The above introduces how to write the PHP stack, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.