PHP _ basics: php Basics. PHP _ basic, php basic directory array function class and object string operation session control time and date exception handling I. array 1. index array header (Content-Type: texthtml; c PHP _ basics, php Basics
Directory
- Array
- Function
- Class and object
- String operation
- Session Control
- Time and date
- Exception handling
I. array
1. index array
Header ("Content-Type: text/html; charset = utf-8"); // create an empty array $ str = array (); // index array: the keys of an array are integers, and the order of keys starts from 0, and so on. $ Fruit = array ("Apple", "banana", "pineapple"); // index array value assignment: // 1. assign the value $ arr [0] = 'apple' using the brackets following the name of the array variable. // use the => symbol to separate the key and value. The left side indicates the key, value on the right. Array ('0' => 'apple'); // count ($ arr) returns the array length // for loop access to the value in the index array for ($ I = 0; $ I
";}// Foreach cyclically accesses the value in the index array foreach ($ fruit as $ k =>$ v) {echo $ k." ...... ". $ v ."
";}
2. associate an array
Header ("Content-Type: text/html; charset = utf-8"); // associate an array: the index Group Key is a string array $ fruit = array ('apple' => "apple", 'bana' => "banana ", 'pineapple' => "pineapple"); // assign a value to the associated array // 1. assign the value $ arr ['apple'] = 'apple' using the brackets following the name of the array variable. // 2. use the => symbol to separate keys and values. the left side indicates the key, and the right side indicates the value array ('apple' => 'apple '); // foreach loop access the value of foreach ($ fruit as $ k => $ v) {echo 'in the associated array'
English fruit key name: '. $ k.', corresponding value: '. $ v ;}
II. Functions
1. variable functions
// Variable function. call the function name () {echo 'job';} $ func = 'name' using the variable value; // call the variable function $ func ();
2. determine whether a function exists
function func() {}if (function_exists('func')){ echo 'exists';}
III. classes and objects
// Define a class Car {// define the attribute public $ name = 'auto'; // define the method public function getName () {// The $ this pseudo variable can be used inside the method to call the property or method return $ this-> name ;}// instantiate an object $ car = new Car (); // call the object method echo $ car-> getName (); // class attributes // public: public // protected: protected, protected attributes cannot be called externally // private: private; private attributes cannot be called externally // static methods: objects do not need to be instantiated when static methods are used, you can call it directly by class name. The operator is double colon: class Car {public static function getName () {return 'auto' ;}} echo Car: getName (); // The result is "car" // construct_construct (): This function is called every time an object is created. // destructor _ destruct (): call this function class Car every time an object is destroyed {// add constructor and Destructor function _ construct () {print "constructor called \ n ";} function _ destruct () {print "destructor called \ n" ;}}$ car = new Car ();
IV. string operations
1. differences between single and double quotation marks
// The double quotation mark string directly contains the string variable // the content in the single quotation mark string is regarded as a common character $ str = 'hello'; echo "str is $ str "; // running result: str is helloecho 'Str is $ str '; // running result: str is $ str
2. remove spaces at the beginning and end of the string
// Trim removes spaces at both ends of a string. // Rtrim is to remove the right space of a string // ltrim is to remove the left space trim ("space") of a string ");
3. get the length of the string
// English character length strlen ($ str); // Chinese character length mb_strlen ($ str, "UTF8 ");
4. string truncation
// Truncation function substr () // substr (string variable, start position, number of interceptions) $ str = 'I love you'; echo substr ($ str, 2, 4); // The Chinese string truncation function mb_substr () // mb_substr (string variable, start position, number of interceptions, webpage encoding) $ str = 'I love you, china'; echo mb_substr ($ str, 4, 2, 'utf8 ');
5. string search
// Strpos (the string to be processed, the string to be located, and the starting position of the positioning [optional]) $ str = 'I want to study at imooc '; $ pos = strpos ($ str, 'imooc ');
6. string replacement
// Str_replace (string to be searched, string to be replaced, string to be searched, replacement for counting [optional]) $ str = 'I want to learn js '; $ replace = str_replace ('js', 'php', $ str );
7. string merging and Segmentation
// String merging function implode (): combines array elements into a string // implode ([optional] delimiter, array) $ arr = array ('hello', 'World! '); $ Result = implode ('', $ arr); print_r ($ result); // The result shows Hello World! // String separator function explode (): returns an array composed of strings // explode ([optional] delimiter, string) $ str = 'Apple, banana '; $ result = explode (',', $ str); print_r ($ result); // The result shows array ('apple', 'banana ')
V. session control
1. cookie
// Set the cookie // name (Cookie name). you can access it through $ _ COOKIE ['name'] // value (Cookie value) // expire (Expiration Time) unix timestamp format. the default value is 0, indicating that the browser is disabled. // path (valid path) if the path is set to '/', the entire website is valid. // domain (valid domain) by default, the entire domain name is valid. if 'www .imooc.com 'is set, $ value = 'test'; setcookie ("TestCookie", $ value) is valid only in the www subdomain name ); // valid for one hour setcookie ("TestCookie", $ value, time () + 3600); // delete cookie and Expiration time setcookie ('test', '', time () -1 );
2. session
// First run the session_start method to enable sessionsession_start (); // use the global variable $ _ SESSION to read and write sessions. $ _ SESSION ['name'] = 'job'; echo $ _ SESSION ['name']; // delete a sessionunset ($ _ SESSION ['name']); // delete all sessionsession_destroy ();
VI. time and date
// UNIX timestamp: the sum of the seconds from 00:00:00, January 1, January 1, 1970 to the current time. // Function time () to obtain the timestamp $ time = time (); echo $ time; // date () function of the current time of the server, to get the current date // date (the format of the timestamp, specifying the timestamp [default is the current date and time, optional ]) // set the default time zone date_default_timezone_set ('Asia/Shanghai'); // output the corresponding 1396193923 date echo date ("Y-m-d "); // implement the strtotime function: Get the timestamp of a certain date or get the timestamp of a certain time // strtotime (the time string to be parsed, returns the timestamp (optional) of the return value. The default value is the current time.) // 1398700800, this number indicates that 1398700800 seconds of echo strtotime ('2017-04-29 ') have elapsed since 00:00:00, January 1, 2014; // 1398700801, this number indicates that the echo strtotime ('2017-04-29 00:00:00 ') was January 1, 1970 seconds from 00:00:01, January 1, 1398700801 to 00:00:01, 2014 ');
VII. Exception handling
// Create a function that can throw an exception: function checkNum ($ number) {if ($ number> 1) {throw new Exception ("Exception prompt-the number must be less than or equal to 1");} return true;} // trigger an Exception in the "try" code block try {checkNum (2 ); // if an Exception is thrown, the following line of code will not be output echo. 'If you can see this prompt, your number is less than or equal to 1';} catch (Exception $ e) {// capture exception echo 'capture exception :'. $ e-> getMessage ();} // Exception has several basic attributes and methods, including: // message exception message content // code exception code // file the file name that throws an exception // line throws an exception on the number of lines in the file // common methods include: // getTrace get Exception tracing information // getTraceAsString get Exception tracing information string // getMessage get error information class MyException extends Exception {function getInfo () {return 'custom error information'; }}try {throw new MyException ('error');} catch (Exception $ e) {echo $ e-> getInfo ();}
Handler directory array function class and object string operation session control time and date exception handling I. array 1. index array header ("Content-Type: text/html; c...