search
HomeBackend DevelopmentPHP TutorialPHP basic knowledge code summary

PHP basic knowledge code summary

Jul 02, 2018 am 11:57 AM
php

一、PHP基础语法 变量到数组

<?php
       //phpinfo();
       
       /* 变量
       $a=1;//不分配空间
       echo "\$a=".$a;
       echo "<br/>";
       var_dump($a);// 结果为NULL
       echo "hello worrld";*/
       
       /* int型最大能表示多大
        echo "<br/>".PHP_INT_SIZE;
       echo "<br/>".PHP_INT_MAX;//(2的31次方-1) 31:4*8-1个符号位
       $a=-2147483648;
       echo "<br/>".$a;
       var_dump($a);//超过int型 范围 则会变为float类型*/
       
       /* 布尔值
       $d=0.0;
       if(!$d){
           echo "!!";
           }*/
       /* 浮点数
       浮点数精度是14(从左边开始,第一个非0就是精度的开始)*/
       
       /*字符型
       
       单引号和双引号区别
       
       $d=90;
       $d1="$d";
       $d2=&#39;$d&#39;;
       echo $d1;
       echo $d2;*/
       
       //$a=7/5.1;
       //echo $a;
       
       # === 包括类型也相等
       /*$a=2;
       $b=2.0;
       if($a!=$b)
       {
           echo"!=";
           }
           if($a!==$b)# !== 包括类型也不相等
           {
               echo "!==";
               }*/
       
       /*  &&和||只要前面的一个为真假即不执行后一个 
           and 和 or 则不是
           or的优先级比=低  所以  
           $e=false or true; //结果为false,因为此时$e先赋值为FALSE
           var_dump($e);
           $f=true and false;//结果为true,因为此时$e先赋值为true
           var_dump($f);*/
           
       /*字符串拼接
          $a="1";$b="2";
          $c=$a.$b;
       */
       
       /* 对象类型运算符
       
       class Dog{}
       $dog=new Dog;
       var_dump($dog instanceof Dog);
       
       $a=3;
       echo $a++*3;//9*/
       
       /*常量
       define("TAX_INT",21);
       #$TAX_INT=9;
       echo TAX_INT;
       
       const TAX_TWO=0.3;
       echo "<br/>".TAX_TWO; */
       
       /*
       #require &#39;other.php&#39;;//不会判断是否重复,可能导致重复输出
       require_once &#39;other.php&#39;;// 先判断是否有重复引入
       
       #include &#39;111other.php&#39;;
       #include_once &#39;other.php&#39;;
       
       #require 和include区别:
          #include如果出现了错误会继续执行,
        #而require则会终止程序
       
       #echo "22";
       
       $i=2;
       $result=getNum($i);//传值,也可以传地址&
       echo $result;*/
       
       /*全局变量 global
       $a=1;
       function get()
       {
           global $a;//可作用于局部内了
           $a++;
           }
           get();
           echo $a;
       */
       
       /*数组初始化
       //$array=array(1.2,12,"wrwe",true);
       //echo count($array);
       
       $arr=array("log"=>"daomul","mima"=>123);
       echo count($arr)."<br/>";
       foreach($arr as $key=>$val)
       {
            echo $key."=".$val."<br/>";
           }
           
           $arr2=array(""=>"32",1=>"fdsf",23,23);
           echo $arr2[""]."<br/>";
           echo $arr2[2]."<br/>";
           
           #使用true作为下标,即是1 ,false :0;  null:""
           
           $arr3=array(123.4=>"arr3");
           echo $arr3[123]."<br/>";
           
           #显示详细数组信息
           print_r($arr3); echo "<br/>";
           var_dump($arr3);
           
           #数组可以动态增长
           $arr4=array(2,3);
           echo $arr4[1]."<br/>";
        $arr4[2]=&#39;11 22 333 444&#39;;
        #echo $arr4[2];
        
        #字符串的拆分 explode
        $arr=explode(" ",$arr4[2]);
        print_r($arr);
        
        foreach($arr as $key=>$val)# (要循环的数组 as 数组下标变量)
        {
            echo "<br/>$key=>$val";
            }
            
            echo "<br/>".$arr[1];
            unset($arr[1]);#销毁数组元素后,关键字下标不会被重新填充组合
            print_r($arr);*/
            
            /*数组运算 叠加
            $a=array("a"=>12,"b"=>23);
            $b=array("a"=>21,"c"=>43);
            $a=$a+$b;
            print_r($a);*/
            
            
?>

二、数组

 

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
    </head>
    <body>
        <h1 id="nbsp-同一个界面传输参数"> 同一个界面传输参数</h1>
        
        <?php
          /* 在 input中加 value="<?php echo $grades; ?>" 仿造百度搜索 */
         error_reporting(E_ALL ^ E_NOTICE);
        $grades=$_REQUEST[&#39;grade&#39;];  
        $grade=explode(" ",$grades);
        $all=0;
        foreach($grade as $k=>$v)
        {
            $all+=$v;
        }
      ?>
    
        <form action="test.php" method="post">
            <input type="text" name="grade"  value="<?php echo $grades; ?>"/>
            <input type="submit" value="start"/>
        </form>
        
        <?php
           echo "总的:".$all;        
        ?>
    </body>
</html>

 三、静态变量

<?php
      class Child
      {
          public static $num=0;
          public $name;
          function __construct($name) //只有new之后才能调用
          {
              $this->name=$name;
              }
              //静态变量不能用this来访问
          public function join()
          {
              self::$num+=1;  //可以: Child::$num
              echo $this->name."you"; 
          }    
      }
      
      $child1=new Child("k");
      $child1->join();
      $child1=new Child("a");
      $child1->join();
      $child1=new Child("b");
      $child1->join();
      echo "<br/>".Child::$num;
      //类外只能是  类名::变量,
          //类内就能两种
?>

四、继承/封装/多态/抽象

/*class Child
      {
          public static $num=0;
          public $name;
          //构造方法
          function __construct($name) //只有new之后才能调用
          {
              $this->name=$name;
              }
              //静态变量不能用this来访问
          public function join($ifee)
          {
              self::ifee+=1;  //可以: Child::$num
              echo $this->name."you"; 
          }    
      }
      
      $child1=new Child("k");
      $child1->join();
      $child1=new Child("a");
      $child1->join();
      $child1=new Child("b");
      $child1->join();
      echo "<br/>".Child::$num;
      //类外只能是  类名::变量,
          //类内就能两种*/
          
          
          
   //静态方法不能采用非静态变量,只能使用非静态变量
    // 成员函数之间相互调用,需要用  $this->text();
    
    //继承
    
    //1、子类只能继承一个父类
    // 如果想多重继承可以考虑通过多次继承:
    /*class A{}
    class B extends A{}
    class C extends B{}*/
    
    //2、父类中的构造方法,在创造一个子类的对象实例的时候不会默认自动调用
    //3、 子类中调用父类的方法   
        //父类名::方法名(); /  parent::方法名(); parent小写的
        
    //覆盖:
         # 子类的方法和父类的方法名称和参数个数完全一样,但不要求参数名相同
         # 但是修饰符可以不同,但是子的范围〉=父类范围
         # 父类是private则不能覆盖
    /*class A{
        function F(){
           echo " 父类在此!<br/>";
        }
    }
    class B extends A{}
    class C extends B{
        function F(){
            echo "调用了父类了<br/>";
            parent::F();
            A::F();
        }
    }
    $C1=new C();
    $C1->F();*/
    
    //抽象类:父类中不需要被实例化,只让子类继承,也可以被调用里面的;达到代码复用
    
      #抽象类   abstract class name{}
      #抽象方法 abstract public cry();
      #抽象类不一定也有抽象方法
      #类包含抽象方法则必须为抽象类
      #子类继承抽象父类,则必须为抽象类或者实现继承的所有,所有!方法
      
      
      //接口:interfacde 接口{//属性 //方法} 
       #  只能定义规范,让类去实现接口 ,不能自己实现,
       #  class c implements 接口{}
       #  接口不能被实例化/接口能继承其他多个接口/不能不为public
       # 一个类实现了一个接口,必须把接口以及其继承的接口的方法全部实现
       # (1 多个平级的类都要实现某个功能,只是实现方式不同,没有继承关系,  
       #(2 项目经理定规范,让其他程序员实现
       /*interface Stu
       {
             const A=90; 
          public function add();    
       }
       interface Stu2{}
       
       class MyStu implements Stu,Stu2
      {
          public function add()
          {
              echo "dddd".Stu::A."<br/>";
          }
      }
      $mystu=new MyStu();
      $mystu->add();
       echo "OK".Stu::A; #获得接口中的常量*/
       
       //final 使类中的方法不被覆盖
       # final 不能修饰成员属性
       /*class A
       {
           final public function get($salary)
           {
             return $salary*3;
               }
       }
       class B extends A
       {
            public function get($sal)
            {
              return $sal*2;    
            }
           }
           $b=new B();
           $b->get("21"); #Cannot override final method A::get() */
           
           //const常量
           # 要赋初始值;不能后面赋值;不能加$等修饰符
           # self::A ; 类名::A ;接口名::A;  等方式获得常量A的值

五、文件操作以及错误处理

 

<?php
  
  // 文件操作
  /*处理错的方式1
  if(!file_exists("file1.txt"))
  {
      echo "not here";
      exit();
  }
  else
  {
      $fp=fopen("file1.txt","r");
      echo "文件已打开";
      fclose($fp);
  }*/
  
  /* 处理错的方式2
  if(!file_exists("a.txt"))
  {
      die("wenjianbucunzai");
  }
  else
  {}
  echo "end";*/
  /*处理错的方式1
  
  file_exists("b.txt") or die("zhen de ");
  echo "end";
  */
  
  //定义错误函数
  /*function my_error($error,$err_message)
  {
    echo "<font size=&#39;5&#39; color=&#39;red&#39;> $error </front><br/>";//2
    //echo "错误信息是:".$err_message;
    exit();
      }
  //改变系统默认的错误处理函数(“用户自己定义的错误输出函数”,“错误类型”)
   set_error_handler("my_error",E_WARNING);
   $fp=fopen("aa.txt",&#39;r&#39;);*/
   
   //错误触发器
   
   function my_error3($error,$err_message)
   {
         echo "错误号:".$error;
       }
       function my_error4($error,$err_message)
       {
           echo "big big!";
           }
   set_error_handler("my_error3",E_USER_WARNING);//
   set_error_handler("my_error4",E_USER_ERROR);//致命错误,不继续执行
   $age=140;
   if($age>120)
   {
       //调用触发器的时候指定错误级别
         trigger_error("输入的数字过大!",E_USER_ERROR);
         //trigger_error("输入的数字过大!",E_USER_WARNING);
         //exit();
       }
       echo "ok";
?>

 六、错误日志

<?php
 
 //错误日志 php.ini 中的error_log的配置
 
 function my_error5($error,$err_meaasge)
 {
       $err_info="错误信息:".$error."--".$err_meaasge;
       //echo time();
       //输出 当前日期
       //     调整时区:默认时期是UTC和中国差8小时 PRC 或者Asia/Chongqing
       
       date_default_timezone_set("PRC");
      
       echo date("Y-m-d G-i-s");
       echo "<br/>".$err_info;
       
       #将错误存入系统文件中
       error_log("时间是:".date("Y-m-d G-i-s")."-".$err_info."\r\n",3,"myerror.txt");//3个参数
     }
     set_error_handler("my_error5",E_USER_WARNING);
     $i=1;
     if($i<2)
     {
         trigger_error("输入的数字过小",E_USER_WARNING);
     }
?>

 七、捕获异常

<?php
  
  //处理异常
  #注意事项:异常抛出之后,得代码不会被继续执行
  #抛出异常之后如果没用处理则会报错
  try
  {
      addUser("1a");
  }
  catch(Exception $e)
  {
      echo "失败信息:".$e->getMessage();//getLine()
      #可以继续抛出 throw $e;
      #也可以顶一个顶级异常处理
      # $i=8/0  fopen("a.txt","r") 很难抛出异常
  }
  
  function addUser($user)
  {
      if($user=="a")
      {
         echo "登陆成功!";
      }
      else
      {
         throw new Exception("用户名错误!");
      }
  
  }
  
  /*#顶级异常处理
  function my_error()
  {
      echo "我是顶级异常处理!".e->getMeaasge();
  }
  set_error_handler("my_error");*/
?>


 

 相关推荐:

PHP调用ffmpeg对视频截图并拼接脚本

Yii2中的场景(scenario)和验证规则(rule)的详解

MixPHP、Yii和CodeIgniter的并发压力测试的小结

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The above is the detailed content of PHP basic knowledge code summary. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)