首页 养生问答 疾病百科 养生资讯 女性养生 男性养生

PHP多态代码实例

发布网友 发布时间:2022-04-22 06:09

我来回答

2个回答

懂视网 时间:2022-04-06 05:31

PHP实例方法的例子有:1、PHPExcel读取Excel,2、获取文本中首张图片地址;3、将图片保存到本地;4、返回JSON数据;5、【var_dump】函数改写;6、图片转为base格式等等。

PHP实例方法的例子有:

  • PHPExcel 读取Excel

  • 获取文本中首张图片地址

  • 将图片保存到本地

  • 返回JSON数据

  • var_dump 函数改写

  • 图片转为base格式

  • 使用curl 实现get请求

  • 使用curl 实现post请求

  • 简单的xml转数组方法

  • Utf-8转统一码

  • 字符串转统一编码

  • 获取IP地址

  • 创建随机字符串

  • 根据生日获取年龄

  • 根据经纬度计算距离

  • PHPExcel 读取excel

    function readExcel($filename, $encode = 'utf-8')
    {
    // import("ORG.Util.PHPExcel.IOFactory");
     import("Org/Util/PHPExcel");
     if (strpos($filename, "xlsx")) {
     $objReader = PHPExcel_IOFactory::createReader('Excel2007');
     } else {
     $objReader = PHPExcel_IOFactory::createReader('Excel5');
     }
     $objReader->setReadDataOnly(true);
     $objPHPExcel = $objReader->load($filename);
     $objWorksheet = $objPHPExcel->getActiveSheet();
     $highestRow = $objWorksheet->getHighestRow();
     $highestColumn = $objWorksheet->getHighestColumn();
     $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
     $excelData = array();
     for ($row = 1; $row <= $highestRow; $row++) {
     if ((string)$objWorksheet->getCellByColumnAndRow(0, $row)->getValue() == "") continue;
     for ($col = 0; $col < $highestColumnIndex; $col++) {
      $value = (string)$objWorksheet->getCellByColumnAndRow($col, 1)->getValue();
      if ($value == "") {
      continue;
      }
      $excelData[$row - 1][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
     }
     }
     return $excelData;
    }

    获取文本中首张图片地址

    function getFirstPic($content){
     if(preg_match_all("/(src)=(["|']?)([^ "'>]+.(gif|jpg|jpeg|bmp|png))2/i", $content, $matches)){
     $str=$matches[3][0];
     if(preg_match('//ueditor/php/upload/image/',$str)){
      return $str1=substr($str,6);
     }
     }
    }

    将图片保存到本地

    function getImage($url,$save_dir='',$filename='',$type=1){
     if(trim($url)==''){
     return array('file_name'=>'','save_path'=>'','error'=>1);
     }
     if(trim($save_dir)==''){
     $save_dir='./';
     }
     if(trim($filename)==''){//保存文件名
     $ext = strrchr($url,'.');
     if($ext!='.gif'&&$ext!='.jpg'){
      return array('file_name'=>'','save_path'=>'','error'=>3);
     }
     $filename=time().$ext;
     }
     if(0!==strrpos($save_dir,'/')){
     $save_dir.='/';
     }
     //创建保存目录
     if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
     return array('file_name'=>'','save_path'=>'','error'=>5);
     }
     //获取远程文件所采用的方法
     if($type){
     $ch=curl_init();
     $timeout=5;
     curl_setopt($ch,CURLOPT_URL,$url);
     curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
     curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
     $img=curl_exec($ch);
     curl_close($ch);
     }
     else{
     ob_start();
     readfile($url);
     $img=ob_get_contents();
     ob_end_clean();
     }
     $size=strlen($img);
     echo $size;
     //文件大小
     $fp2=fopen($save_dir.$filename,'a');
     fwrite($fp2,$img);
     fclose($fp2);
     unset($img,$url);
     return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
    }

    返回JSON数据

    function show($status, $msg, $closeCurrent=false, $data=array()){
     $tmpArr = array(
     'statusCode' => $status,
     'message' => $msg,
     'closeCurrent' => $closeCurrent,
     );
     $tmpArr = array_merge($tmpArr, $data);
     exit(json_encode($tmpArr));
    }

    var_dump 函数改写

    function lyl_dump($content){
     header("Content-type:text/html;charset=utf-8");
     echo '<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />';
     echo "<pre>";
     var_dump($content);
     echo "<pre/>";
     die;
    }

    图片转为base格式

    function baseEncodeImage ($image_file) {
     if(!file_exists($image_file)){
     return false;
     }
     $image_info = getimagesize($image_file);
     $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
     $base_image = chunk_split(base_encode($image_data));
     return $base_image;
    }

    使用curl 实现get请求

    function httpGet($url) {
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($curl, CURLOPT_TIMEOUT, 500);
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); //这个是的ssl校验,需要验证
     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); //
     curl_setopt($curl, CURLOPT_URL, $url);
     $res = curl_exec($curl);
     curl_close($curl);
     return $res;
    }

    使用curl 实现post 请求

    function httpPost($url,$post_data){
     $curl = curl_init();
     $post_data = json_encode($post_data);
     curl_setopt($ch , CURLOPT_URL , $url);
     curl_setopt($ch , CURLOPT_HEADER , 0 );
     curl_setopt( $ch, CURLOPT_POST, 1);  //设置为POST方式
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch , CURLOPT_POSTFIELDS , $post_data);
     $rst = curl_exec( $ch );
     curl_close( $ch );
     return $rst;
    }

    简单的xml转数组方法

    function simplexml_to_array($simplexml_obj, $array_tags = array(), $strip_white = 1)
    {
     if ($simplexml_obj) {
     if (count($simplexml_obj) == 0)
      return $strip_white ? trim((string)$simplexml_obj) : (string)$simplexml_obj;
     $attr = array();
     foreach ($simplexml_obj as $k => $val) {
      if (!empty($array_tags) && in_array($k, $array_tags)) {
      $attr[] = simplexml_to_array($val, $array_tags, $strip_white);
      } else {
      $attr[$k] = simplexml_to_array($val, $array_tags, $strip_white);
      }
     }
     return $attr;
     }
     return FALSE;
    }

    Utf-8转统一码

    function utf8_to_unicode($char)
    {
     switch (strlen($char)) {
     case 1:
      return ord($char);
     case 2:
      $n = (ord($char[0]) & 0x3f) << 6;
      $n += ord($char[1]) & 0x3f;
      return $n;
     case 3:
      $n = (ord($char[0]) & 0x1f) << 12;
      $n += (ord($char[1]) & 0x3f) << 6;
      $n += ord($char[2]) & 0x3f;
      return $n;
     case 4:
      $n = (ord($char[0]) & 0x0f) << 18;
      $n += (ord($char[1]) & 0x3f) << 12;
      $n += (ord($char[2]) & 0x3f) << 6;
      $n += ord($char[3]) & 0x3f;
      return $n;
     }
    }

    字符串转统一编码

    function str_to_unicode_word($str,$depart=' ')
    {
     $arr = array();
     $str_len = mb_strlen($str,'utf-8');
     for($i = 0;$i < $str_len;$i++)
     {
     $s = mb_substr($str,$i,1,'utf-8');
     if($s != ' ' && $s != ' ')
     {
      $arr[] = 'ux'.utf8_to_unicode($s);
     }
     }
     return implode($depart,$arr);
    }

    获取IP地址

    function getIP()
    {
     static $realip;
     if (isset($_SERVER)) {
     if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
      $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
     } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
      $realip = $_SERVER["HTTP_CLIENT_IP"];
     } else {
      $realip = $_SERVER["REMOTE_ADDR"];
     }
     } else {
     if (getenv("HTTP_X_FORWARDED_FOR")) {
      $realip = getenv("HTTP_X_FORWARDED_FOR");
     } else if (getenv("HTTP_CLIENT_IP")) {
      $realip = getenv("HTTP_CLIENT_IP");
     } else {
      $realip = getenv("REMOTE_ADDR");
     }
     }
     return $realip;
    }

    创建随机字符串

    function createNonceStr($length = 16)
    {
     $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567";
     $str = "";
     for ($i = 0; $i < $length; $i++) {
     $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
     }
     return $str;
    }

    根据生日获取年龄

    function get_age($birthday){
     if($birthday){
     list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthday));
     list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
     $age = $y2-$y1;
     if(intval($m2.$d2) < intval($m1.$d1)) {$age -= 1;}
     return $age;
     }else{
     return "未知";
     }
    }

    根据经纬度计算距离

    function getDistance($lat1, $lng1, $lat2, $lng2)
    {
     $earthRadius = 6367000; 
     $lat1 = ($lat1 * pi() ) / 180;
     $lng1 = ($lng1 * pi() ) / 180;
     $lat2 = ($lat2 * pi() ) / 180;
     $lng2 = ($lng2 * pi() ) / 180;
     $calcLongitude = $lng2 - $lng1;
     $calcLatitude = $lat2 - $lat1;
     $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
     $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
     $calculatedDistance = $earthRadius * $stepTwo;
     return round($calculatedDistance);
    }

    相关免费学习推荐:php编程(视频)

    热心网友 时间:2022-04-06 02:39

    这篇文章主要介绍了PHP多态代码实例,本文用2个代码实例来演示PHP中的多态,需要的朋友可以参考下
    多态定义:只关心一个接口或者基类,而不关心一个对象的具体类。(同一类型,不同结果)
    这里两个例子:
    第一个,我们发现,基类定义了标准,子类进行了自我规则的实现。这是多态的一个要求。同时,这是满足重写;实际上这是不同类的不同表现;没有严格满足一个接口,或者基类编程。因为你调用的时候不是
    stu-showGrade()
    而是各自自己的方法;
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    class
    stu{
    public
    function
    showGrade(){
    echo
    base
    class;
    }
    }
    class
    xiaomin
    extends
    stu{
    public
    function
    showGrade(){
    echo
    is
    son
    show
    80;
    }
    }
    class
    xiaoli
    extends
    stu{
    public
    function
    showGrade(){
    echo
    is
    son
    show
    60;
    }
    }
    function
    doit($obj){
    if(get_class($obj)
    !=
    stu){
    $obj-showGrade();
    }
    }
    doit(new
    xiaoli());
    doit(new
    xiaomin());
    第二个例子:dovoice
    参数规定了$obj
    为animal,意识就是用接口
    接受了
    实现类对象。了向上转型。这就符合同一类型,不同结果了,这就是多态;
    实际上在Java中
    会是
    animal
    a
    =
    new
    dog();这样子的;因为PHP
    是若类型语言。没有对象转型机制。
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    interface
    animal{
    public
    function
    voice();
    }
    class
    cat
    implements
    animal{
    public
    function
    voice(){
    echo
    miao~~~br;
    }
    }
    class
    dog
    implements
    animal{
    public
    function
    voice(){
    echo
    wang
    ~~~br;
    }
    }
    function
    dovoice(animal
    $obj){
    $obj-voice();
    }
    dovoice(new
    dog());
    dovoice(new
    cat());

    声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com