首页 > 代码库 > 【面霸2】
【面霸2】
//1、使对象可以像数组一样进行foreach循环,要求属性必须是私有。(Iterator模式的PHP5实现,写一类实现Iterator接口)
class MyClass implements Iterator{
private $vars = array();
private $var1;
private $var2;
private $var3;
function __set($name , $value){
$this->vars[$name] = $value;
}
function __get($name){
return $this->vars[$name];
}
public function rewind() {
reset($this->vars);
}
public function current() {
return current($this->vars);
}
public function key() {
return key($this->vars);
}
public function next() {
return next($this->vars);
}
public function valid() {
return $this->current() !== false;
}
}
$it = new MyClass($values);
$it->var1 = 1;
$it->var2 = 2;
$it->var3 = 3;
foreach ($it as $a => $b) {
print “$a: $b“;
}
//2、用PHP实现一个双向队列
class DoubleEndedQueue{
protected $elements;
public function __construct(){
$this->elements = array();
}
public function push($element){
array_unshift($this->elements , $element);
}
public function pop(){
return array_shift($this->element);
}
public function inject($element){
$this->elements[] = $element;
}
public function eject(){
array_pop($this->elements);
}
}
//3、请写一段PHP代码,确保多个进程同时写入同一个文件成功
function write_file($filename, $content){
$lock = $filename . ‘.lck‘;
$write_length = 0;
while(true) {
if( file_exists($lock) ) {
usleep(100);
} else {
touch($lock);
$write_length = file_put_contents($filename, $content, FILE_APPEND);
break;
}
}
if( file_exists($lock) ) {
unlink($lock);
}
return $write_length;
}
//4、有一个一维数组,里面存储整形数据,请写一个函数,将他们按从大到小的顺序排列。要求执行效率高。并说明如何改善执行效率。
function BubbleSort(&$arr){
$cnt=count($arr);
$flag=1;
for($i=0;$i<$cnt;$i++) {
if($flag==0){
return;
}
$flag=0;
for($j=0;$j<$cnt-$i-1;$j++){
if($arr[$j]>$arr[$j+1]){
$tmp=$arr[$j];
$arr[$j]=$arr[$j+1];
$arr[$j+1]=$tmp;
$flag=1;
}
}
}
}
$test=array(1,3,6,8,2,7);
BubbleSort($test);
var_dump($test);
//5、PHP获取远程web服务器时间的代码
function get_time($server){
$data = "http://www.mamicode.com/HEAD / HTTP/1.1/r/n";
$data .= "Host: $server\r\n";
$data .= "Connection: Close\r\n\r\n";
$fp = fsockopen($server, 80);
fputs($fp, $data);
$resp = ‘‘;
while ($fp && !feof($fp))
$resp .= fread($fp, 1024);
preg_match(‘/^Date: (.*)$/mi‘,$resp,$matches);
return strtotime($matches[1]);
}
echo date(‘Y-m-d H:i:s‘,get_time("outofmemory.cn"));
【面霸2】