PHP Basic Knowledge Code Summary

Source: Internet
Author: User
First, PHP base syntax variable to array

<?php//phpinfo ();       /* variable $a =1;//do not allocate space echo "\ $a =". $a;       echo "<br/>"; Var_dump ($a);//The result is a null echo "Hello Worrld"; *////* int type maximum can indicate how much echo "<br/>".       Php_int_size; echo "<br/>".       php_int_max;//(2 of 31 square-1) 31:4*8-1 sign bit $a =-2147483648;       echo "<br/>". $a;       Var_dump ($a);//The range of int is changed to float type */* Boolean $d = 0.0;           if (! $d) {echo "!!";       }*//* Floating-point number precision is 14 (starting from the left, the first non-0 is the beginning of precision) */* character single and double quotation marks $d = 90;       $d 1= "$d";       $d 2= ' $d ';       echo $d 1;       echo $d 2;*///$a =7/5.1;              echo $a;       # = = = include type also equal/* $a = 2;       $b = 2.0;           if ($a! = $b) {echo "! =";               } if ($a!== $b) #!== include type also unequal {echo "!=="; }*//* && | | As long as the previous one is true or false, then an and and or is not executed and the priority ratio = Low So $e =false or true;           The result is false, because at this point the $e is first assigned to False Var_dump ($e);          $f =true and false;//result is true, because at this point $e is first assigned true var_dump ($f); */* string concatenation $a = "1"; $b = "2";       $c = $a. $b;       */* Object type operator class dog{} $dog =new Dog;              Var_dump ($dog instanceof Dog);       $a = 3;       echo $a ++*3;//9*//* constant define ("Tax_int", 21);       # $TAX _int=9;              Echo Tax_int;       Const tax_two=0.3; echo "<br/>". Tax_two;              */* #require ' other.php ';//do not determine whether duplicate, may lead to duplicate output require_once ' other.php ';//First determine if there is a repetition of the introduction       #include ' 111other.php ';              #include_once ' other.php ';              #require and include differences: #include如果出现了错误会继续执行, #而require则会终止程序 #echo "22";       $i = 2;       $result =getnum ($i);//Pass the value, also can pass the address & echo $result; */* global variable globally $a = 1; function get () {GloBal $a;//can be used in the local $a + +;           } get ();       echo $a;       */* Array initialization//$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/> ";           } $arr 2=array ("+ =" + ",1=>" FDSF ", 23,23); echo $arr 2[""].           <br/> "; Echo $arr 2[2]. "                      <br/> ";  #使用true作为下标, that is 1, false:0;           Null: "" $arr 3=array (123.4=> "ARR3"); Echo $arr 3[123]. "                      <br/> "; #显示详细数组信息 Print_r ($arr 3);           echo "<br/>";                      Var_dump ($arr 3);           #数组可以动态增长 $arr 4=array (2,3); Echo $arr 4[1]. "        <br/> ";        $arr 4[2]= ' 11 22 333 444 ';                #echo $arr 4[2]; #字符串的拆分 Explode $arr =explode ("", $arr 4[2]);        Print_r ($arr);            foreach ($arr as $key + $val) # (array of arrays as array subscript variable to loop) {echo <br/> $key = $val ";            } echo "<br/>". $arr [1]; Unset ($arr [1]); #销毁数组元素后, the keyword subscript is not refilled with the combined Print_r ($arr); */* Array operation overlay $a =array ("a            "=>12," B "=>23);            $b =array ("A" =>21, "C" =>43);            $a = $a + $b; Print_r ($a); */?>

Second, array


Third, static variables

<?php      class child      {public          static $num =0;          public $name;          function __construct ($name)//Only new can call          {              $this->name= $name;              }              A static variable cannot access the public          function join ()          {self              :: $num +=1;  Can: Child:: $num              Echo $this->name. " You ";           }          }            $child 1=new Child ("K");      $child 1->join ();      $child 1=new Child ("a");      $child 1->join ();      $child 1=new Child ("B");      $child 1->join ();      echo "<br/>". Child:: $num;      Outside the class can only be the  class name:: Variable,          //class can be two kinds of?>

Iv. Inheritance/encapsulation/polymorphism/abstraction

/*class Child {public static $num = 0;          Public $name;              Constructor method function __construct ($name)//Only new can call {$this->name= $name;  }//Static variable cannot use this to access public function join ($ifee) {self::ifee+=1; Can: Child:: $num echo $this->name. "           You ";      }} $child 1=new child ("K");      $child 1->join ();      $child 1=new Child ("a");      $child 1->join ();      $child 1=new Child ("B");      $child 1->join (); echo "<br/>".      Child:: $num; Class can only be a class name:: Variable,//class can be two * *///Static methods can not take non-static variables, can only use non-static variables//member functions call each other, need to use $this        ->text ();        Inheritance//1, subclasses can inherit only one parent class//If you want multiple inheritance you can consider inheriting through multiple:/*class a{} class B extends a{} class C extends b{}*/ 2, the construction method in the parent class, when creating an object instance of a subclass does not default automatically call//3, the child class calls the parent class method//Parent class Name:: Method Name (); /Parent:: Method name (); Parent lowercase//overwrite: #The subclass's method and parent class have exactly the same method name and number of arguments, but do not require the same parameter name # but the modifier can be different, but the range of the child 〉= the parent class range # Parent class is private you cannot overwrite/*class a{function F () {echo ' Parent class here!        <br/> ";            }} class B extends a{} class C extends b{function F () {echo "called The parent class <br/>";            Parent::f ();        A::f ();    }} $C 1=new C (); $C 1->f (); *//abstract class: The parent class does not need to be instantiated, only the subclass inherits, can also be called inside; code reuse #抽象类 abstract class name{} #抽象方法 abstract P      Ublic cry (); #抽象类不一定也有抽象方法 #类包含抽象方法则必须为抽象类 #子类继承抽象父类, you must be an abstract class or implement all of the inherited, all!       Method//Interface: INTERFACDE interface {//attribute//Method} # can only define specification, let class to implement interface, cannot implement by itself, # Class C implements interface {}         # interfaces cannot be instantiated/interfaces can inherit other interfaces/cannot fail to implement an interface for public # A class must implement the interface and the method of its inherited interface all # (more than 1 classes of class to implement a function, but the implementation of different ways, there is no inheritance relationship,           # (2 project manager set specifications, let other programmers implement/*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 the methods in the class are not overwritten # Final cannot decorate member properties/*class A {final public function               Get ($salary) {return $salary;                }} class B extends A {public function get ($sal) {return $sal * *;           }} $b =new B (); $b->get ("21"); #Cannot Override final Method A::get () *///CONST constant # To assign an initial value, no subsequent assignment; f::a;  Class name:: A; Interface name:: A; The value of constant A is obtained by equal means.

V. File manipulation and error handling

<?php//File operation/* Handle the wrong way 1 if (!file_exists ("file1.txt")) {echo "Not here";  Exit ();      } else {$fp =fopen ("File1.txt", "R");      echo "File is open";  Fclose ($FP);  }*//* Handle the wrong way 2 if (!file_exists ("A.txt")) {die ("Wenjianbucunzai");  } else {} echo "end",/*//* Handle the wrong Way 1 file_exists ("B.txt") or Die ("Zhen de");  echo "End"; *///Definition Error function/*function my_error ($error, $err _message) {echo "<font size= ' 5 ' color= ' Red ' > $error &LT;/FRONT&G    T;<br/> ";//2//echo" error message is: ". $err _message;      Exit ();   }//Change the system default error handling function ("User-defined error output function", "error Type") Set_error_handler ("My_error", e_warning);       $FP =fopen ("Aa.txt", ' r '); *//Error trigger function My_error3 ($error, $err _message) {echo "Error number:". $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);//Fatal error, do not continue execution $age =   140;    if ($age >120) {   When invoking a trigger, specify the error level Trigger_error ("the number entered is too large!")         ", E_user_error); Trigger_error ("The number entered is too large!")         ", e_user_warning);       Exit (); } echo "OK";? >

Vi. error logs

<?php  //error log php.ini in Error_log configuration  function My_error5 ($error, $err _meaasge) {       $err _info= "error message:". $ Error. " --". $err _meaasge;       echo time ();       Output current date       //     adjust time zone: The default period is UTC and China difference 8 hours PRC or asia/chongqing              date_default_timezone_set ("PRC");             echo Date ("y-m-d g-i-s");       echo "<br/>". $err _info;              #将错误存入系统文件中       Error_log ("Time is:". Date ("Y-m-d g-i-s"). " -". $err _info." \ r \ n ", 3," Myerror.txt ");//3 parameters     }     set_error_handler (" My_error5 ", e_user_warning);     $i =1;     if ($i <2)     {         Trigger_error ("the number entered is too small", e_user_warning);     }? >

Vii. Catching exceptions

<?php    //Handling exception  #注意事项: After the exception is thrown, the code will not be executed  #抛出异常之后如果没用处理则会报错  try  {      addUser ("1a");  }  catch (Exception $e)  {      echo "failure message:" $e->getmessage ();//getline ()      #可以继续抛出 throw $e;      #也可以顶一个顶级异常处理      # $i =8/0  fopen ("A.txt", "R") is difficult to throw an exception  }    function AddUser ($user)  {      if ($ user== "a")      {         echo "landed successfully! ";      }      else      {         throw new Exception ("User name is wrong!");}    }    /* #顶级异常处理  function my_error ()  {      echo "I am the top exception handler! ". E->getmeaasge ();  }  Set_error_handler ("My_error");*/?>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.