preface

I want to ask myself why I want to learn PHP, what is PHP, what CAN I do after learning PHP, the future development, so how to learn a programming language, how to give learning advice.

PHP is a hypertext preprocessor learning language, it is a widely used open source multipurpose scripting language, it can be embedded in HTML, especially suitable for Web development.

PHP is a scripting language embedded in HTML documents executed on the server side. The language is similar in style to THE C language and is now widely used by many web programmers. You can develop interactive, dynamic web pages using PHP.

So how do you understand dynamic web pages? Here’s what follows:

What’s the difference between a dynamic website and a static website?

  1. Dynamic Site: a site that can interact with a database
  2. Static Sites: cannot interact with databases

And what do words like LAMP stand for? Common in PHP:

So what is a LAMP?

  1. L:LINUX
  2. A:Apache
  3. M:mysql
  4. P:PHP

Expandable to say the following vocabulary, we need to understand step by step.

PHP environment setup (LAMP,LNMP,LNMPA)

LAMP: Linux+Apache+MySQL+PHP

LNMP: Linux+Nginx+MySQL+PHP

LNMPA: Linux+Nginx+MySQL+PHP+Apache

WAMP: Window+Apache+MySQL+PHP

Integrated environment: WAMPServer, XAMPP, PHPStudy

Apache, web server

Apache is the world’s top web server software, it can run on almost all widely used computer platforms, because of its cross-platform and security is widely used, is one of the most popular Web server software. It is fast, reliable, and extensible with a simple API.

So let’s step into the world of PHP and understand its syntax.

Basic grammar

PHP document structure: 1. 2. Note that file names should not use Chinese characters or contain special characters

PHP style:

  • The standard style

Here’s a code example:

<? PHP code snippets; ? >Copy the code
  • Short style

Here’s a code example:

<? Code; ? >Copy the code

Note: You need to configure short_open_tag=On in the PHP configuration file php.ini and restart the Apache server

  • ASPStyle:

Here’s a code example:

<% code segment; % >Copy the code

Note: You need to configure asp_tags=On in the PHP configuration file php.ini and restart the Apache server

PHP syntax style examples:

<? php echo'this is dada show dada'; <! DOCTYPE html><html>
  <head>
    <meta charset="utf-8">
    <title>55555 - <? php echo 'hello world'; ? ></title>
    <style media="screen">
      h1{
        color: <? php echo'5555'; ? >; }</style>
    <script type="text/javascript">
      alert('hello world');
    </script>
  </head>
  <body>
    <h1>this is dadada show time<? php echo 'dada'; ? ></h1>
  </body>
</html><? Echo 'this is a dada'; echo 'this is a dada'; echo '<br/>';

echo 'hello world';
*/

echo 'this is dada show time';
Copy the code

You need tools to learn PHP, and here is phpStorm, which is often used

Tell me aboutphpstormInstallation and use of

Phpstorm is a commercial PHP integrated development tool developed by JetBrains that is ready to help users code, run unit tests, or provide visual debugging.

download

Enter the official website of PHPStorm and click the “downLoad” button to enter the downLoad page.

Finally, double-click the desktop icon.

PHP syntax

PHP file naming Considerations:

Considerations for variables:

Data type:

Special symbols:

The difference between single and double quotation marks

  1. Double quotes parse variables, single quotes do not parse variables
  2. Single quotation marks are fast
  3. Double quotes parse all escape characters, single quotes parse only\and\ \These two escape characters

The meaning of curly braces

  1. Turn variables into a whole
  2. The first kind of${variable name} Variable name;
  3. The second,{$variable name variable name};

Temporary transformations are implemented in functional form

  1. Intval (variable)Converted to an integer
  2. Strval (variable)Convert to a string
  3. Boolval (variable)To a Boolean type

Permanent transformation

  1. settype(Variable, set type) Sets the type of the variable
  2. gettypeRetrieves the type of the variable

The variable library detects variable types

  1. is_int(variable) > test integer
  2. is_string(variable) > Detect string type
  3. is_array(variable) > Check the array type
  4. is_resource(variable) > Detect the resource type
  5. is_object(Variable) > Test object type
  6. is_null(variable) > Detect null type
  7. is_numeric(Variable) > Detect numeric type

constant

  • Q: What is a constant?
  • A constant, as opposed to a variable, cannot be modified during script execution

The system constant

  1. PHP_VERSION: getphpversion
  2. PHP_OS: Gets the operating system of the server
  3. M_PI:PIThe value of the
  • Matters needing attention:
  1. Not preceded by the constant name$symbol
  2. Start with a letter or underscore and use capital letters whenever possible
  3. Constants are defined and cannot be changed or undefined
  4. Constants can only have scalar values. Resources can be used, but are not recommended
  5. Constants are case sensitive by default

Checks whether a constant is defined

  1. definedfunction
  2. var_dump(definedVariables)

Magic constant

  1. __LIEN__Get the line number
  2. __FILE__Get the full path and filename of the file
  3. __FUNCTION__The name of the function
  4. __CLASS__class
  5. __METHOD__methods
  6. __DIR__Return to the file path

Connect our variables in the form of dots

Generate a verification code randomly

Let’s take a look at the following example code:

<! DOCTYPE HTML >< HTML >< head lang="en"> <meta charset="UTF-8"> <title></title> <script SRC =" jquery-22.3.js" type="text/javascript"></script> </head> <body> <? php header("content-type:text/html; charset=utf-8"); $str = ''; $rand = mt_rand(1000, 9999); $str.='<span style="color:rgb('.mt_rand(0, 255).', '.mt_rand(0, 255).','.mt_rand(0, 255).') ">'.mt_rand(0, 9).'<span>'; $str.='<span style="color:rgb('.mt_rand(0, 255).', '.mt_rand(0, 255).','.mt_rand(0, 255).') ">'.mt_rand(0, 9).'<span>'; $str.='<span style="color:rgb('.mt_rand(0, 255).', '.mt_rand(0, 255).','.mt_rand(0, 255).') ">'.mt_rand(0, 9).'<span>'; $str.='<span style="color:rgb('.mt_rand(0, 255).', '.mt_rand(0, 255).','.mt_rand(0, 255).') ">'.mt_rand(0, 9).'<span>'; ? > <label for="check"> Please enter verification code :</label> <div id="hiddent_val" style="display: none; > <? php echo $str ? ></div> <input type="text" name="check" id="check_val"/><? php echo $str; ? > <br/> <input type="button" onclick="javascript:check();" Value = "submit" / > < script > function check () {var v1 = $(" # hiddent_val "). The text (); v1 = v1*1; var v2=$("#check_val").val(); v2 = v2*1; if(v1==v2){ alert('true'); }else{ alert('false'); } } </script> </body> </html>Copy the code

Date function

Date function format code:

data($format[,$time=time()]) time(): Y: year, M: month, D: day, h: hour, I: minute, s: second W: Monday to Sunday 0 indicates Sunday. Date_default_timezone_get () date_default_timezone_set($timezone);Copy the code

Predefined variable

Predefined variables: defined variables in the system, including:

  1. $_POST:httppostVariable to receive the formpostMode to send data
  2. $_GET:HTTPgetVariable, receive to?Data that is passed as a parameter
  3. $_FILES:HTTPFile upload variable
  4. $_SERVER: Server and execution environment variables
  5. $_ENV: Environment variables
  6. $_SESSION: session variable
  7. $_COOKIE:HTTP Cookies
  8. $_REQUEST:$_GET+$_POST+$COOKIE
  9. $php_errormsgPrevious error message
  10. $GLOBALSSuper global, a built-in variable that is always available in all scopes

Switch… case

Let’s take a look at Switch… Example code for case is as follows:

<? php $a = 2; switch ($a){ case 1: echo 'a<br/>'; break; case 2: echo 'b<br/>'; break; case 3: echo 'c<br/>'; break; Default: echo 'default execution '; }Copy the code

For the sample

Let’s look at the following example code for:

<? $sum = 1; $sum = 1; $sum = 1; for($i=0; $i<101; $i++){ $sum = $sum+$i; } echo $sum; echo '<hr/>'; // for($I =1; $i<101; ${i++) if ($I % 2 = = 0) {echo 'this is can be divided exactly by 2:'. $I. '< br / >'; }}Copy the code

Learn the following examples – multiplication table code:

<? php /* 1*1=1; * 1*2=2 2*2=4 * */ for($i=1; $i<=9; $i++){ for($j=1; $j<=$i; $j++){ echo $j.'*'.$i.'='.($i*$j)."\t"; } echo '<br/>'; }Copy the code

Special flow control

Special process control – Example:

<? PHP //break for($I =1; $i<10; $i++){ if($i==3){ break; $I.'<br/>'; } echo '<hr/>'; //continue for($I =1; $i<10; $i++){ if($i==3){ continue; $I.'<br/>'; } echo '<hr/>'; Echo 'Here is the beginning '; goto jump; Echo 'here is the code below jump '; Jump: echo 'here is the code in jump '; echo '<hr/>'; Echo 'Here is the end ';Copy the code

PHP arrays

What is a PHP array? What is an array? – Array: a collection of data. In PHP an array is actually an ordered map.

Declared by array() :

  1. array()An empty array
  2. Array (value 1, value 2...)An array of contiguous indices starting at 0
  3. array(key=>value,key=>value...)You can declare indexed arrays and associations

Print the array with: print_r

Array or mixed array:

  1. Array keys can be integers or strings
  2. If the key name is not an integer or a string, the following cast is performed
  3. A string containing a valid integer value is converted to an integer
  4. A floating point integer is converted to an integer type
  5. BooleantrueConvert to 1,falseConversion of 0
  6. nullConverts to an empty string
  7. Arrays and objects cannot be used as key names

Dynamically and quickly create arrays

Create an array dynamically:

  1. $Name of the array[]: index array with consecutive subscripts
  2. $Name of the array[number]: Specifies the array index
  3. $Name of the array[String]Associative array

Quick Array creation – Sample format:

range($min, $max[$step=1]); Quickly create indexed array Compact ($varname,...) ; Quickly create associative arraysCopy the code

Learn some examples:

<? php // $arr = array(); // var_dump($arr); $arr = array(1, 5.5, false, 'dada'); print_r($arr); echo '<hr/>'; //array(key=>value,key=>value...) $arr1 = array (5 = > 'dada, 6 = > 12, 9 = > false, 4 = > 4.4); print_r($arr1); echo '<hr/>'; // associative array, subscript string //username can be called our key name, $arr2 = array('username'=>'dada', 'password'=>123456, 'age'=>27); print_r($arr2); echo '<hr/>'; / / index + associated mixed use $arr3 = array (1, 2, 3, 4, 5, 'username' = > 'dadaqianduan', 'addr' = > 'haha'); print_r($arr3); echo '<hr/>'; $arr3['username'] = 'dada'; print_r($arr3);Copy the code

Traverses the array through the array pointer function

  1. current($arr)Gets the key value of the element where the current pointer is located
  2. key($arr)Gets the key name of the element where the current pointer is located
  3. next($arr), moves the array pointer down one bit and gets the key value of the element where the array pointer is located
  4. prev($arr), moves the array pointer up one bit and returns the key value of the element where the current pointer is located
  5. end($arr)Moves the array pointer to the end of the array and returns the key value of the current element
  6. reset($arr)Moves the array pointer to the beginning of the array and returns the key value of the current element

The array is traversed by foreach

Foreach (array as $key=>$val){}Copy the code

Iterate through the array with list and each

  1. list($var[,$var...] ): Assigns values from an array to variables
  2. each($arr)Returns the current key/value pair in the array and moves the array pointer down one bit

User list page

Example code for creating a user list page is in the following format:

<tr style="text-align:center;" > </tr> <? php foreach($userInfo as $val){ ? > <tr style="text-align:center;" > <td><? php echo $val['id']; ? ></td> <td><img src="img/<? php echo $val['id']; ? >" alt=""/></td> </tr> <? php }? >Copy the code

Adding a Message Page

Example code format for adding a message page is as follows:

</h2> <form action=" doaction.php? Act =add" method="get"> <table border="1" width="80%" cellPADDING ="0" cellpadding="0" bgcolor="blue"> <tr> <td> < td > < input type = "text" name = "username" id = "" placholder =" please enter your said "/ > < / td > < / tr > < / table > < / form > < / body >Copy the code

Submit reflection – doaction.php

<? php $username = $_GET['username']; $title = $_GET['title']; $content = $_GET['content']; $arr[] = array( 'username' => $username, 'title' => $title, 'content' => $content ); print_r($arr);Copy the code

Collecting message information:

$filename = 'text.txt';
$data = 1;
file_put_contents($filename, $data);
Copy the code

<input type="hidden" name="act" value="add"/> ? php $username = isset($_GET['username']) ? $_GET['username'] : ''; $time = date('Y-m-d h:i:s'); $act = isset($_GET['act']) ? $_GET['act']:''; If (file_exists($filename) && filesize($filename)>0){$STR = file_get_contents($filename); $arr = unserialize($str); } if($act == 'add'){ ... $arr = serialize($arr); file_put_contents($filename, $arr); }Copy the code
if($act == 'add') { $arr[] = array( 'username' => $username, 'title' => $title, 'content' => $content, 'time' => $time ); $arr = serialize($arr); If (file_put_contents($filename, $arr)){echo' add message '; }else{echo 'add message failed '; }; }Copy the code

PHP function

To summarize the nine common functions, let’s see what they mean and what they do:

  1. strlen($string)Get the length of the string
  2. Find string:
  • strpos($string,$search[,$offset]): Finds the first occurrence of the target string in the specified string
  • stripos($string,$search[,$offset]): Search regardless of case
  • strrpos($string,$search[,$offset]): Finds the last occurrence of the target string in the specified string
  • strripos($string,$search[,$offset]): search for the last location regardless of case
  • strstr|strchr($string,$search[,$before_needle]): Looks for the first occurrence of a string, returning a string
  • strrchr($string,$search): Finds the last occurrence of a specified character in a string
  • stristr($string,$search[,$before_needle]): Search regardless of case
  • str_replace($search,$replace,$string): Searches for another string in the specified string and replaces it with the specified string
  • str_ireplace($search,$replace,$string): search and replace regardless of case
  1. String case
  • strtolower($string): Returns the string after lowercase
  • strtoupper($string): Returns the uppercase string
  • ucwords($string)Capitalize the first letter of a word
  • ucfirst($string): capitalizes the first letter of the word in the string
  • lcfirst($string): Lowercase the first letter of the word in the string
  1. ASCII characters
  • ord($char): gets the ASCII value of the specified character
  • chr($ascii): Gets the specified character according to ASCII
  1. Interception of a string
  • substr($string,$start[,$length]): Intercepts a string
  • substr_replace($string,$replace,$start[,$length]):Replaces a substring of a string
  1. encryption
  • md5($string): Evaluates the MD5 hash value of the string32A string of bits
  • sha1($string): Evaluates the hash value of sha1 of the string, and returns40A string of bits
  1. Filtering:
  • trim($string[,$charlist]): Filters Spaces at both ends of a string by default. You can also filter a specified string
  • ltrim($string[,$charlist]): Filters the left end of the string
  • rtrim | chop($string[,$charlist]): Filters the right end of the string
  • strip_tags($string[,$allowTag]): Filters HTML tags in strings
  • addslashes($string): uses a backslash to reference special characters in a string
  • htmlentities($string[,$flag=ENT_COMPAT]): Converts all characters to HTML entities
  • htmlspecialchars($string[,$flag=ENT_COMPAT]: Converts special characters in a string to HTML entities
  • nl2br($string): to the string\nwith<br/>replace
  1. Split/merge
  • explode($delimiter,$string)Splits the specified string into arrays
  • implode | join($delimiter,$array)Concatenate the key values in an array into a string with the specified delimiter
  • str_split($string[,$split_length=1])Convert strings to arrays
  1. Commonly used functions
  • strrev($string)Inverted string
  • str_shuffle($string)Randomly shuffled string
  • str_repeat($string)Repeated string
  • str_getcsv(...)Parse the CSV string into an array
  • parse_str($str[,$arr])Parsing a string into multiple variables

The following contents are presented in table form

The table of mathematical function library is as follows:

function instructions
abs($number) Beg absolute value
ceil($number) Into an integer
floor($number) Drop the decimal part
round($number,$percision) rounded
pow($base,$exp) Power operation
sqrt($number) The square root
max($val1,$val2,..) For maximum
min($val1,$val2...) For the minimum
mt_rand($min,$max) Random number generation

Datetime function library table is as follows:

function instructions
date_default_timezone_get() Get the default time zone
date_default_timezone_set($timezone) Setting the Default Time Zone
date($format[,$time]) Get the date and time of the server
time() Get the current timestamp
mktime() Gets a Unix timestamp for a date
getdate($timestamp) Get date and time information
gettimeofday($return_float) Get current time
microtime([$get_as_float]) Returns the current Unix timestamp and subtlety number
strtotime($time[,$now=time()]) Parses the date and time description of any English text tounixThe time stamp

Create an array operation

function describe
range($min, $max[,$step=1]) Quickly create contiguous index arrays
compact($varname,$varname...) Quickly create associative arrays
array_fill($start_index,$num,$value) Fills the array with the given value
array_fill_keys($keys,$value) Populates the array with the specified key and value
array_combine($keys,$values) Create an array with the value of one array as its key and the value of the other as its key

Key-value operations are shown in the following table:

function describe
count() Count the number of cells in an array or the number of attributes in an object
array_keys($array) Gets the array’s key name as a contiguous index array
array_values($array) Returns the key value of an array as a contiguous index array
array_filp($array) Swap key names and assignments in arrays
in_array() Checks if a value exists in the array
array_search() Searches the array for the given value, returning the corresponding key name on success
arry_key_exists() Checks whether the given key name or index exists in the array
array_reverse() An array of the horse
shuffle() Scrambles the elements of the array
array_rand() Randomly fetching the array’s key name
array_unique() Removes duplicate values from the array
array_sum() Counts the sum of the element values in an array

Array pointer functions are as follows:

function describe
key($array) Gets the key name of the element where the current pointer is located
current($array) pos($array) Gets the key value of the element where the current pointer is located
next($array) Moves the array pointer down one bit and returns the key value of the element where the current pointer is located
prev($array) Moves the array pointer up one bit and returns the key value of the element where the current pointer is located
end($array) Moves the array pointer to the end of the array and returns the key value of the element where the current pointer is located
reset($array) Moves the array pointer to the beginning of the array and returns the key value of the element where the current pointer is located
each($array) Returns the current key-value pair in the array and moves the array pointer down one bit
list($var,...) Assigns the value of the element in the array to the corresponding variable
array_unshift($array,$value...) Inserts one or more elements at the beginning of an array
array_shift($array) Ejects the first element of the array
array_push($array,$value...) Pushes one or more elements to the end of the array
array_pop($array) Ejects the last element of the array

Array split and merge table is as follows:

function describe
array_slice($array,$offset) Interception of array
array_merge() Merge array

Use of custom functions

How do you declare functions? Take a look at the following code:

Function Function name ([parameter...]) ){function body; Return Return value; }Copy the code

Matters needing attention:

  • The function name should contain no special characters and start with a letter or underscore followed by a alphanumeric underscore
  • Function names should be clear and start with a verb
  • Function names should be humped or underlined
  • Function names cannot be the same
  • Function names are case insensitive, but it is best to follow case when calling them
  • Function arguments are not required
  • The function returns Null by default, or a return value can be added by return

Now let’s look at the function arguments we put in:

Parameters are divided into parameters and arguments:

Parameter, which is declared when the function is defined. (Mandatory: The parameter must be passed when the function is called. Optional argument: use the default value if no argument is passed when calling the function;)

Argument, which is actually passed in when the function is called

Next, look at the scope of variables as shown in the following mind map:

Here is the difference between passing a value and passing a reference to a function:

  1. Changes made to a variable in the function body do not affect the variable itself
  2. Passing references Changes to variables in the function body affect the variables themselves

The callback function

What is the callback function?

When you want to perform multiple unrelated operations on a single object or value during development, callbacks are the best way to do this.

<? PHP function text1(){echo 'I am dadda '; } function text2($username){echo 'I am Nezha '; } // The callback function: the name inside the function is the argument we are passing in (); function callBack($call,$str){ $call($str); CallBack ('text2','dadaqianduan'); callBack(' dadaqianduan');Copy the code

Recursive function

What is a recursive function, where the function body calls itself

Example of writing:

function text($i) {
 echo $i;
 $i--;
 if($i>=0){
  text($i);
 }
}

text(2);
Copy the code

Anonymous functions

Anonymous function examples:

$str = function() { echo 'dadaqianduan'; }; $str(); $str1 = function($username) { echo 'dada'; echo $username; }; $str1 (' which zha ');Copy the code

PHP includes files

PHP files include: include,include_once,require,require_once, which includes the contents of one file into another file.

  • requireReference file error is an error and a warning
  • includeThere are two warnings when referencing a file incorrectly
  • Error handling:requireA fatal error is generated and the script stops
  • Error handling:includeOnly warnings are generated and the script continues

So use include!

The include or require statement retrieves all text, code, and tags that exist in the specified file and copies them to the file that uses the include statement.

The syntax is as follows:

include 'filename'; Or the require 'filename';Copy the code

PHP include example:

Let’s create a standard footer file called ‘dada.php’ as follows:

<? PHP echo '<p> '; ? >Copy the code

You then need to reference the footer file in another page as follows:

< HTML > <body> <p> php include 'footer.php'; ? > </body> </html>Copy the code

Require_once/include_once, and the require/include effect is the same, different is executed when will first check if the target content in have imported before, if the import, so will not repeat the introduction of the same content.

object-oriented

What is object orientation first?

It’s an idea, it’s a way of developing, it’s not actual code.

Speaking of object orientation, it is necessary to talk about the difference between object orientation and process orientation:

  1. In fact, process-oriented emphasis is on functional behavior (how one thing is done)
  2. Object orientation is the encapsulation of functionality into objects, emphasizing the functionality of objects (who does a thing)
  3. Object-oriented features: inheritance, encapsulation, polymorphism

Several ways to Orient:

Object Oriented Analysis (OOA) Object Oriented Design (OOP) Object Oriented ProgrammingCopy the code

Classes and objects

Speaking of object orientation is inseparable from the relationship between classes and objects: a class is an abstraction of a concrete transaction, and an object is a concrete instance of this class.

How to define a class, class definition :(similar to the class keyword to define)

class Person{ } <? $userName = 'dada'; $userName = 'dada'; $userName = 'dada'; public $age = 12; $p = new Person(); echo $p->userName.'<hr/>'; echo $p->age.'<hr/>';Copy the code

Properties say, talk about the method, the following example:

<? php class Person{ public $userName; public $age; Public function eat() {echo 'I want to eat '; } } $p = new Person(); $p->eat();Copy the code

Object allocation in memory

In PHP, memory is divided into four categories:

  1. Data segment: used to store the program has been initialized and not 0 global variables such as: static variables and constants
  2. Code snippets: store functions, methods
  3. Stack space segment: Stores small data
  4. Heap space segment: Stores references to objects and data with large volumes

PHP access modifier

What are the access modifiers? As shown below:

  1. publicPublic, default
  2. protectedThe protected
  3. privateprivate

An example of this code is as follows

<? php class Da{ public $userName = 'dada'; protected $age = 12; Public function eat() {echo 'I want to eat '; } } $da = new Da(); Echo $da->userName echo $da->ageCopy the code

Modified as follows:

<? php class Da{ public $userName = 'dada'; protected $age = 12; Public function eat() {echo 'I want to eat '; //$this echo $this->age; } } $da = new Da(); echo $da->userName echo $da->eat()Copy the code

Constructors and destructors

What is a constructor in the first place? The constructor is called when passing a new object.

What is the secondary destructor? Destructors must first take no arguments. Destructors are called before all references to the object have been removed or the display has disappeared.

<? php class Person { public $userName; public $age; Public function Person() {// echo 'I am a constructor '; Public function _construct($this->userName = $age) {$this->userName = $this; $this->age = $age; Public function _destruct(){echo 'destruct'}} $p1 = new Person('dada',12); echo $p1->userName $p1 = null; // The destructor is calledCopy the code

Set and GET magic methods

Understand the set and GET methods: SET provides a way to set a member’s properties to the outside world, and GET provides a way to access a member’s properties.

So the magic constants: _set and _get.

The following is an example:

<? php class Person{ private $userName; private $age; public function setAge($age){ // $this->age = 12; // $this-age == private $age; $this->age = $age; } public function getAge(){ return $this->age; } public function _set($key,$value){ $this->userName = $value; } public function _get($key){ return $this->userName; } $p = new Person(); // echo $p->userName; $p->setAge(16); echo $p->getAge();Copy the code

Isset and unset magic methods

  1. _issetWhen external callsisset()Function is called automatically when it detects unreachable or nonexistent properties.
  2. _unsetWhen called outside the classunsetAutomatically called when an unreachable property is destroyed.

The following is an example:

<? php class Person{ private $userName; private $age; public $abc; public function _construct($userName,$age){ $this->userName=$userName; $this->age=$age; } public function _isset($name){echo 'when isset() is called to detect unreachable attributes or non-existent attributes '; return isset($name); // Boolean} public function _unset($name){echo 'when unset is called outside the class to destroy an unreachable attribute '; } } $p = new Person('dada',12); var_dump(isset($p->userName)); // echo '<hr/>' unset($p->abc);Copy the code

inheritance

Here are the characteristics of inheritance in object-oriented inheritance, encapsulation, and polymorphism:

So what’s the point of inheritance? You can reduce code duplication by using inheritance through the extends keyword.

A code example is as follows:

<? php class Person{ public $userName; public $age; public function eat(){ echo 'dadaqianduan'; } } class Student extends Person{ } $stu = new Student(); echo $stu->eat();Copy the code

useparentThe keyword

Parent is used in inheritance with the following code:

<? php class Person { public $userName='parent'; public $age = 100; Protected function eat() {echo 'eat'; } } class Student extends Person { public $userName = 'children`; public $age = 12; Public function eat() {parent::eat().'<hr/>'; echo 'children'; } } $stu = new Student(); echo $stu->eat();Copy the code

Use the final keyword

Precautions for using the final keyword:

  • finalKeywords cannot modify properties
  • befinalmodifiedclassAnd methods cannot be inherited or overridden

Use the static keyword

Static is used to express the meaning of being static:

  1. bestaticThe modified properties and methods are static properties and methods
  2. Static properties and methods are characterized by the fact that they are not invoked through objects
  3. Properties and methods can be invoked by class names

The following code is an example:

class Person {
 public static $i = 1;
 public static function eat(){
  echo '要吃饭';
 }
}
echo Person::$i;
Person::eat();
Copy the code

Self accesses static properties and methods inside the class via self:

The following code is an example:

class Student {
 public static $i = 1;
 public static function eat(){
  echo self::$i;
 }
}
Student::eat();
Copy the code

The following example static binding can be used as follows:

<? php class A{ public static function text1(){ echo 'text1'; } public static function text2(){ echo 'text2'; self::text1(); } } class B extends A { public static function text1(){ echo 'B-A'; } } B::text2();Copy the code

Use the const keyword

Const, is a constant modifier. Constants must be capitalized, cannot be accessed through objects, and do not require the $sign.

Student Management System

Example Database connection:

<? PHP header (" content-type: text/HTML. charset=urf-8"); $link = mysqli_connect('localhost','root','root') or die(' connection failed '); Mysqli_set_charset ($link,'utf8'); // open mysqli_select_db($link, 'dadaqianduan'); $query = "insert user values(1,'dada','12345') "; $res = mysqli_query($link, $query); If ($res){echo 'insert data successfully '; }else{echo 'failed to insert data '; }Copy the code

So mysqli operates on the database in the following steps:

  1. The connectionmysql
  2. Set character set
  3. Open the specified database
  4. performsqlThe query
  5. Release result set
  6. Close the connection

If we need to rewrite the connection database each time we use it, we can encapsulate it:

Encapsulate array: config.php

<? php $config = array( 'host'=>'localhost', 'user'=>'root', 'password'=>'root', 'charset'=>'utf8', 'dbName'=>'dadaqianduan' ); define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PWD','root'); define('DB_CHARSET','utf8'); define('DB_DBNAME','dadaqianduan');Copy the code

The connection

<? PHP /** * connect * @param string $host * @param string $user * @param string $password * @param string $charset * @param Function connect1($host,$user,$password,$charset,$database){$link = Mysqli_connect ($host,$user,$password) or die(' failed to connect '); mysqli_set_charset($link,$charset); Mysqli_select_db ($link,$database) or die(' select_db '); return $link; }Copy the code

The connection requires passing an array

* @param array $config * @return object */ function connect2($config){ $link=mysqli_connect($config['host'],$config['user'],$config['password']); mysqli_set_charset($link,$config['charset']); Mysqli_select_db ($link,$config['dbName'] or die(' select_db '); return $link; }Copy the code

Establish a connection in constant form

@return unknown */ function connect3(){$link = mysqli_connect(DB_HOST,DB_USER,DB_PWD) or Die (' database connection failed '); mysqli_set_charset($link,DB_CHARSET); Mysqli_select_db ($link,DB_DBNAME) or die($link,DB_DBNAME); return $link; }Copy the code

The insert

/* array( 'username'=>'dada', 'password'=>'dada', 'age'=>'123456', 'regTime'=>'12345' ); INSERT user(username,password,age,regTime) VALUES('dada','dada','12','123123123'); */ /** * insert operation * @param object $link * @param array $data * @param string $TABLE * @return Boolean */ / insert function insert($link,$data,$table){ $keys=join(',',array_key($data)); $vals = "'".join("','", array_values($data))."'"; $query = "insert{$table}({$keys})values({$vals})"; $res = mysqli_query($link,$query); if($res){ return mysqli_insert_id($link); }else{ return false; }}Copy the code

The update operation

/* array( 'username'=>'dada', 'password'=>'dada', 'age'=>'12', 'regTime'=>'123123123' ); UPDATE user SET username='dada',password='dada',age='12',regTime='123123123' WHERE ID =1 */ ** * $link * @param array $data * @param string $table * @param string $where * @return boolean */ function update($link, $data, $table, $where = null) { foreach ( $data as $key => $val ) { $set .= "{$key}='{$val}',"; } $set = trim ( $set, ',' ); $where = $where == null ? '' : ' WHERE ' . $where; $query = "UPDATE {$table} SET {$set} {$where}"; $res = mysqli_query ( $link, $query ); if ($res) { return mysqli_affected_rows ( $link ); } else { return false; }}Copy the code

Delete operation

//DELETE FROM user WHERE id= /** * DELETE operation * @param object $link * @param string $table * @param string $WHERE * @return boolean */ function delete($link, $table, $where = null) { $where = $where ? ' WHERE ' . $where : ''; $query = "DELETE FROM {$table} {$where}"; $res = mysqli_query ( $link, $query ); if ($res) { return mysqli_affected_rows ( $link ); } else { return false; }}Copy the code

Querying all Records

/ query all records * * * * @ param object $link * @ param string $query * @ param string $result_type * @ the return array | Boolean * / function fetchAll($link, $query, $result_type = MYSQLI_ASSOC) { $result = mysqli_query ( $link, $query ); if ($result && mysqli_num_rows ( $result ) > 0) { while ( $row = mysqli_fetch_array ( $result, $result_type ) ) { $rows [] = $row; } return $rows; } else { return false; }}Copy the code

Gets the number of records in the table

/ get the number of records in a table * * * * @ param object $link * @ param string $table * @ return number | Boolean * / function getTotalRows ($link, $table) { $query = "SELECT COUNT(*) AS totalRows FROM {$table}"; $result = mysqli_query ( $link, $query ); if ($result && mysqli_num_rows ( $result ) == 1) { $row = mysqli_fetch_assoc ( $result ); return $row ['totalRows']; } else { return false; }}Copy the code

Get the number of entries in the result set

* @param object $link * @param string $query * @return Boolean */ function getResultRows($link, $query) $query) { $result = mysqli_query ( $link, $query ); if ($result) { return mysqli_num_rows ( $result ); } else { return false; }}Copy the code

Encapsulation of access to information:

/**
 * @param object $link
 */
function getServerInfo($link) {
	return mysqli_get_server_info ( $link );
}
/**
 * @param object $link
 */
function getClientInfo($link) {
	return mysqli_get_client_info ( $link );
}

/**
 * @param object $link
 */
function getHostInfo($link){
	return mysqli_get_host_info($link);
}

/**
 * @param object $link
 */
function getProtoInfo($link) {
	return mysqli_get_proto_info ( $link );
}
Copy the code

Redis met

The mind map is shown as follows:

Redis is an open source (BSD-licensed), in-memory data structure storage system that can be used as a database, cache, and messaging middleware. It supports many types of data structures, such as strings, hashes, lists, sets, sorted sets, range queries, bitmaps, Hyperloglogs and Geospatial index radius query. Redis is built with replication, LUA scripting, LRU eviction, transactions and different levels of disk persistence, And provides high availability through Redis Sentinel and Automated partitioning (Cluster).

Advantages:

  1. Resident memory, superior read and write performance, far better than hard diskIO
  2. Support a variety of data formats, can achieve a variety of business needs
  3. Data can be automatically saved to hard disks, and services can be restored upon restart

Operate the Redis installation

Under the Windows installation download address: https://github.com/tporadowski/redis/releases.

Redis supports 32 and 64 bits. This needs to be selected according to the actual situation of your system platform, here we download redis-x64-XXx. zip to disk C, decompress, rename the folder Redis.

Open the folder as follows:

Open a CMD window and use the CD command to switch the directory to XXX :\redis run:

redis-server.exe redis.windows.conf
Copy the code

And anothercmdWindows, the original do not close, or you will not be able to access the server.

PHP+MySQL environment variable (phpStudy)

Set whether to take effect:

Composer is a PHP tool for managing dependency relationships. You can declare dependent external libraries in your own projects, and Composer will install these dependent libraries for you.

https://getcomposer.org/

Click on theGetting Started

Click download:

https://developer.aliyun.com/composer?spm=a2c4e.11153940.0.0.40eb6995J6zupg

Check:

Windows quick configuration NodeJS

Command line for configuring taobao mirror source:

npm config set registry http://registry.npm.taobao.org
Copy the code

Windows Quick Configuration Bower

Install phpStudy on Windows

Use Tencent cloud server

fastadmin.net/go/tencent

https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html to download

https://www.bt.cn/?invite_code=MV9veWhubmU=

Click on the install https://www.bt.cn/bbs/thread-19376-1-1.html immediately

yum install -y wget && wget -O install.sh http:/ / download. Bt. Cn/install/install_6. 0. Sh & sh the sh
Copy the code

Domain name Resolution

Error:

Internal Server ErrorThe server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the  server administrator at [email protected] to inform themof the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.
Copy the code

Htaccess is changed to the following

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteCond %{REQUEST_FILENAME} ! -f RewriteCond %{REQUEST_FILENAME} ! -d RewriteRule . /index.php [L] </IfModule>Copy the code
  • Node.js(Optional, used to install Bower and LESS, also used for packing compression)
  • Composer(Optional, used to manage third-party extension packages)
  • Bower(Optional, used to manage front-end resources)
  • Less(Optional, for editing less files, if you need to modify CSS styles, it is best to install)

Pay attention and don’t get lost

Well folks, that’s all for this article, and the people here are talented. I will continue to update the technology related articles, if you find the article useful, welcome to give a “like”, also welcome to share, thank you!!