分类 PHP 下的文章

命名空间namespace的简单介绍

//php文件中引用同名类会产生错误,命名空间即可解决此类问题。
//a.class.php

class Apple{
    public function get_info(){
        echo "this is a.class";
    }
}

//b.class.php

class Apple{
    public function get_info(){
        echo "this is b.clss";
    }
}

//index.php
require_once "a.class.php";
require_once "b.class.php";
//这样直接引用必然会产生致命错误,由此引入命名空间
//在a.class.php顶部添加 namespace a\b\c b.class.php添加 namespace d\e\f
//此时同时引入不会再出错
$a = new a\b\c\Apple();
$a->get_info();
//同理获取b.class
// 为了便于重复使用,直接使用
use a\b\c\Apple;
$a = new Apple();

// 同样在使用b.class时,可以使用as
use d\e\f\Apple as bApple;

//如果存在一个c.class.php存在与底层,即为为设置命名空间
// c.class.php

class Apple{
    public function get_info(){
        echo "this is c.clss";
    }
}

//则此时调用该类则需要在其前面添加\来判定为底层类
$c = new \Apple();

php获取本地ip地址,局域网ip获取

<?php
header("Content-type: text/html; charset=gb2312");

function getLocalIP(){
    exec("ipconfig /all", $output);

    foreach($output as $line){
        if (preg_match("/(.*)IPv4(.*)/", $line)){
            $ip = $line;
            $ip = str_replace("IPv4 地址 . . . . . . . . . . . . :","",$ip);
            $ip = str_replace("(首选)","",$ip);
        }
    }
    return $ip;
}
echo $ip = getLocalIP();

在程序使用时由于使用utf-8,而默认系统为gbk,则考虑使用正则匹配来判断:

if (preg_match("/(.*)IPv4(.*)/", $line)){
     $ip = preg_replace('/.*:/', '', $line);
     $ip = preg_replace('/[^\d^\.]/', '', $ip);
}

使用phpQuery轻松采集网页内容

我们有时需要抓取一个网页的内容,但只需要特定部分的信息,通常会用正则来解决,这当然没有问题。正则是一个通用解决方案,但特定情况下,往往有更简单快 捷的方法。比如你想查询一个编程方面的问题,当然可以使用Google,但stackoverflow 作为一个专业的编程问答社区,会提供给你更多,更靠谱的答案。

- 阅读剩余部分 -

移动设备(手机和平板)环境检测的 PHP 类库Mobile_Detect.php

Mobile Detect 是一个轻量级的开源移动设备(手机和平板)检测的 PHP Class,它使用 User-Agent 中的字符串,并结合 HTTP Header,来检测移动设备环境
这个设备检测的 PHP 类库最强大的地方是,它有一个非常完整的库,可以检测出所用的设备类型(包括操作类型,以及手机品牌等都能检测)和浏览器的详细信息。

- 阅读剩余部分 -

PHP根据城市名获取经纬度

/**

public function get_geo($city){

$url = "http://api.map.baidu.com/geocoder/v2/?ak=wfVfdMthZRL9vjaeyFKiBhLmUth60bbZ&output=json&address=$city";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
/* if(curl_errno($ch)){
 print_r(curl_error($ch));
} */
curl_close($ch);
return json_decode($result,TRUE);

}

Thinkphp设置仅在调试模式关闭时显示404页面

常见thinkphp设置404页面为建一个空控制器;里面然后通过_empty()再$this->display跳转到404页面;
thinkphp的配置项里面是有设置错误页面模板的:
'TMPL_EXCEPTION_FILE' => APP_DEBUG ? THINK_PATH.'Tpl/think_exception.tpl' : './Template/default/Home/Public/404.html',