Basic knowledge of php study notes
Jul 18, 2017 am 09:26 AMi have been studying php for more than a year, and i have accumulated a lot of notes, which are quite complicated. let me write an article to sort them out.
php basic part
<span style="font-family:新宋體">PHP</span>
basic commands for outputting text: <span style="font-family:新宋體">echo</span>
and <span style="font-family:新宋體">print</span>
.
the difference between echo and print
<span style="font-family:新宋體">echo</span>
is a php statement, <span style="font-family:新宋體">print</span>
and <span style="font-family:新宋體">print_r</span>
are functions. statements have no return value, and functions can have return values ??(even if not use )
<span style="font-family:新宋體">echo</span>
to output one or more strings. <span style="font-family:新宋體">print</span>
can only print out the values ??of simple type variables (such as int, string)<span style="font-family:新宋體">print_r</span>
can print out the values ??of complex type variables (such as arrays, objects)
var_dump and print_r difference
<span style="font-family:新宋體">var_dump</span>
returns the type and value of the expression, while <span style="font-family:新宋體">print_r</span>
only returns the result. compared with debugging code, using <span style="font-family:新宋體">var_dump</span>
is easier to read.
variables
variables are used to store values, such as numbers, text strings, or arrays. all variables in php start with a $ symbol.
php variable names are case-sensitive!
php has three different variable scopes:
<code>local(局部)<br>global(全局)<br>static(靜態(tài))</code>
variables declared outside a function have <span style="font-family:新宋體">Global</span>
scope and can only be accessed outside the function.
variables declared inside a function have <span style="font-family:新宋體">LOCAL</span>
scope and can only be accessed inside the function.
the <span style="font-family:新宋體">global</span>
keyword is used to access global variables within a function.
php static keyword
normally, when a function completes/executes, all variables are deleted. however, sometimes i need to not delete a local variable. achieving this will require further work.
to accomplish this, use the static keyword when you first declare the variable:
<code><?php ??? <br>function mytest() {<br>?? static $x=-1;<br>?? echo $x;<br>?? $x--;<br>}<br>mytest();//-1<br>echo "<br>";<br>mytest();//-2<br>echo "<br>";<br>mytest();//-3<br>?></code>
php type
php類型:**php?支持八種原始類型。**
boolean
to specify a boolean value, use the keywords true or false. both are case-insensitive.
integer type
we can use (int) to cast a decimal into an integer.
<code><?php <br>??? var_dump((int)(26/3));//int(8)<br>?></code>
arrays
there are three types of arrays in php:
<code>索引數(shù)組:就是下標(biāo)是順序整數(shù)作為作為索引(比如第幾排第幾列)$class[5]<br>關(guān)聯(lián)數(shù)組:就是下標(biāo)是字符串作為索引(比如名字)$class2["zhangsan"]<br>多維數(shù)組 - 包含一個(gè)或多個(gè)數(shù)組的數(shù)組</code>
the subscript is either an integer or a string.
<code><?php <br>$array = array(<br>??? "foo" => "bar",<br>??? "bar" => "foo",<br>);<br>// 自 php 5.4 起<br>$array = [<br>??? "foo" => "bar",<br>??? "bar" => "foo",<br>];<br>?></code>
array cells can be accessed through the <span style="font-family:新宋體">array[key]</span>
syntax.
note: this does not mean always quoting key names. there is no need to quote the key names of constants or variables, otherwise <span style="font-family:新宋體">PHP</span>
will not be able to parse them.
array operators
example name result $a $b union union of $a and $b $a == $b equality if $a and $b have the same key/ value pairs true $a === $b congruent true if $a and $b have the same key/value pair and are of the same order and type $a != $b unequal if $a is not equal to $ b is true $a $b is not equal. if $a is not equal to $b, it is true$a !== $b is not equal. if $a is not equal to $b, it is true
the <span style="font-family:新宋體">+</span>
operator appends the array elements on the right to the array on the left. if the keys in both arrays are present, only the ones in the left array are used, and the ones on the right are ignored.
object
to initialize an object, use the new statement to instantiate the object into a variable.
commonly used functions
the strlen() function is used to calculate the length of a string.
the strpos() function is used to retrieve a string or a character within a string.
constants
constants can be defined using the define() function. once a constant is defined, it cannot be changed or undefined.
commonly used magic constants:
definition of constant examples:
<code><?php <br>define("poems" , "homeric epic");<br>echo poems ;//outputs "homeric epic" <br>?></code>
php string operators p>
in php, there is only one string operator.
the concatenation operator <span style="font-family:新宋體">(.)</span>
is used to concatenate two string values. for example: echo "a= ".$a."<br>";
the left side of the string literal "a=" is connected to the value of the variable $a, and the second place is connected to the newline character <span style="font-family:新宋體">"<br>"</span>
php function
the function will only be executed when it is called. this is the same as js. similarly, the function definition also uses the function key beginning with the word .
<code><?php <br>??? function sum($x,$y){<br>??????? $z=$x + $y;<br>??????? return $z;<br>??? }<br>??? echo "-2+10= ".sum(-2,10);//outputs "-2+10=8"<br>?></code>
when there is no <span style="font-family:新宋體">return</span>
statement, the above will become "-2 10=";
process control
in here, only the <span style="font-family:新宋體">foreach</span>
statement will be discussed.
the <span style="font-family:新宋體">foreach</span>
statement traverses the output array:
syntax:
foreach?(array_expression?as?$value){?statement}; foreach?(array_expression?as?$key?=>?$value){?statement};
the parameter <span style="font-family:新宋體">array_expression</span>
specifies the array to be traversed, and <span style="font-family:新宋體">$value</span>
is the value of the array
<code><?php <br>???? $actors [0] ="marry";<br>???? $actors [1] ="lorry";<br>???? $actors [2] = "mike";<br>???? foreach ($actors as $values){<br>???? echo "name:$values<br>"; <br>}<br>?></code>
above the code will output:
name:marry
name:lorry
name:mike
two important magic methods
????1.?__set(?)方法:這個(gè)方法用來(lái)為私有成員屬性設(shè)置值的,有兩個(gè)參數(shù),第一個(gè)參數(shù)為你??要為設(shè)置值的屬性名,第二個(gè)參數(shù)是要給屬性設(shè)置的值,沒(méi)有返回值。 ????2.?__get()方法:這個(gè)方法用來(lái)獲取私有成員屬性值的,有一個(gè)參數(shù),參數(shù)傳入你要獲取的成員屬性的名稱,返回獲取的屬性值,這個(gè)方法不用我們手工的去調(diào)用
the methods in php are not case sensitive
require(dirname(__file__).'/global.php');?//引入全局文件 require(dirname(__file__).'/config.ini.php');?//引入基本配置文件
object operator and double colon operator
in the member method of the class, you can use -> (object operator): <span style="font-family:新宋體">$this->property</span>
(where property is the attribute name) to access non-static properties.
static properties are accessed using <span style="font-family:新宋體">::</span>
(double colon): <span style="font-family:新宋體">self::$property</span>
.
=> and ->
<span style="font-family:新宋體">=></span>
array members access symbols, <span style="font-family:新宋體">-></span>
bject members access symbols;<span style="font-family:新宋體">$this</span>
-<span style="font-family:新宋體">>$name=$value</span>
: set the value of the <span style="font-family:新宋體">name</span>
variable of the current class to <span style="font-family:新宋體">$value</span>
;<span style="font-family:新宋體">$this</span>
represents the class itself, <span style="font-family:新宋體">-></span>
is the operator for accessing its class members
double colon operator (<span style="font-family:新宋體">::</span>
) class name <span style="font-family:新宋體">::</span>
static properties/methods
"<span style="font-family:新宋體">::</span>
" is used to call the class static properties and methods
<span style="font-family:新宋體">include()</span>
: includes external files, the syntax format is include (string filename);<span style="font-family:新宋體">require()</span>
: will output an error message and terminate the script<span style="font-family:新宋體">include_once()</span>
: call the same thing multiple times file, the program will only call it once<span style="font-family:新宋體">require_once()</span>
: first check whether the file has been called elsewhere<span style="font-family:新宋體">array_pop()</span>
: get and return the last element in the array<span style="font-family:新宋體">count()</span>
: count the elements in the array number<span style="font-family:新宋體">array_search()</span>
: get the key names of the elements in the array<span style="font-family:新宋體">$array_keys()</span>
: get all the key names of the repeated elements in the array
single quotes and double quotes
php treats the data in single quotes as an ordinary string and does not process it anymore. the double quotes also need to process the strings
get and post
$_get[ ] and $_post[ ] global arrays: used to receive the data passed to the current page by the get and post methods respectively. "[ ]" contains name.
there are three commonly used methods for passing parameters in php: $_post[ ], $_get[ ], $_session[ ], which are used to obtain form, url and session variables respectively. value.
the differences between get and post methods in form submission are summarized as follows:
<code>GET是從服務(wù)器上獲取數(shù)據(jù),POST是向服務(wù)器傳送數(shù)據(jù)。<br>GET 是把參數(shù)數(shù)據(jù)隊(duì)列加到提交表單的ACTION屬性所指的URL中,值和表單內(nèi)各個(gè)字段一一對(duì)應(yīng),在URL中可以看到。POST是通過(guò)HTTP POST機(jī)制,將表單內(nèi)各個(gè)字段與其內(nèi)容放置在HTML HEADER內(nèi)一起傳送到ACTION屬性所指的URL地址。用戶看不到這個(gè)過(guò)程。<br>對(duì)于GET方式,服務(wù)器端用Request.QueryString獲取變量的值,對(duì)于POST方式,服務(wù)器端用Request.Form獲取提交的數(shù)據(jù)。<br>GET傳送的數(shù)據(jù)量較小,不能大于2KB(這主要是因?yàn)槭躑RL長(zhǎng)度限制)。POST傳送的數(shù)據(jù)量較大,一般被默認(rèn)為不受限制。但理論上,限制取決于服務(wù)器的處理能力。<br>GET 安全性較低,POST安全性較高。因?yàn)镚ET在傳輸過(guò)程,數(shù)據(jù)被放在請(qǐng)求的URL中,而如今現(xiàn)有的很多服務(wù)器、代理服務(wù)器或者用戶代理都會(huì)將請(qǐng)求URL記 錄到日志文件中,然后放在某個(gè)地方,這樣就可能會(huì)有一些隱私的信息被第三方看到。另外,用戶也可以在瀏覽器上直接看到提交的數(shù)據(jù),一些系統(tǒng)內(nèi)部消息將會(huì)一 同顯示在用戶面前。POST的所有操作對(duì)用戶來(lái)說(shuō)都是不可見(jiàn)的。</code>
when submitting a form, if the method is not specified, the default is get request (.net default is post), the data submitted in the form will be appended to the url and separated from the url with ?. alphanumeric characters are sent as they are, but spaces are converted to " " signs and other symbols are converted to %xx, where xx is the ascii (or iso latin-1) value of the symbol in hexadecimal. the data submitted by the get request is placed in the http request protocol header, while the data submitted by post is placed in the entity data; the data submitted by get can only be up to 2048 bytes, while post does not have this limit. the parameters passed by post are in the doc, which is the text passed by the http protocol. the parameter part will be parsed when accepting. get parameters. generally it is better to use post. post submits data implicitly, get is passed in the url, and is used to pass some data that does not need to be kept confidential. get is passed in parameters in the url, and post is not.
1. the data requested by get will be appended to the url (that is, the data is placed in the http protocol header) to split the url and transmit the data. the parameters are connected with &
2. the data submitted by get method can only be up to 1024 bytes. in theory, post has no limit and can transfer a larger amount of data. the maximum is 80kb in iis4 and 100kb in iis5
http status code
the difference between cookies and sessions
the contents of cookies mainly include: name, value, expiration time, path and domain. the path and domain together form the scope of the cookie. if the expiration time is not set, it means that the lifetime of this cookie is during the browser session. if the browser window is closed, the cookie will disappear. this type of cookie that lasts for the duration of the browser session is called a session cookie.
session cookies are generally not stored on the hard disk but in memory. of course, this behavior is not specified by the specification. if an expiration time is set, the browser will save the cookies to the hard disk. if you close and open the browser again, these cookies will still be valid until the set expiration time is exceeded.
when the program needs to create a session for a client's request, the server first checks whether the client's request already contains a session identifier
(called session id). if it does, it means it has been previously if a session has been created for this client, the server will retrieve this session according to the session id
and use it (if it cannot be retrieved, a new one will be created). if the client request does not include the session id, a session will be created for this client. and generate a session id associated with this session
the value of the session id should be a string that is neither repeated nor easy to find patterns to counterfeit. this session id will be used in this response is returned to the client for storage. the method of saving this session id can use cookies, so that during the interaction process, the browser can automatically send this id to the server according to the rules.
1. the cookie data is stored on the client's browser, and the session data is stored on the server.
2. cookies are not very safe. others can analyze the cookie stored locally and conduct cookie deception
considering security, session should be used.
3. the session will be saved on the server for a certain period of time. when access increases, it will take up more of your server's performance
in order to reduce server performance, cookie should be used.
4. the data saved by a single cookie cannot exceed 4k. many browsers limit a site to save up to 20 cookies.
5. so personal suggestions:
save important information such as login information as session
if other information needs to be retained, it can be placed in cookie
php code specifications
1. variable assignments must maintain equal spacing and arrangement
2. no extra spaces are allowed at the end of each line
3. ensure the naming of the file and the calling case are consistent because unix-like systems are case-sensitive
4. method names are only allowed to be composed of letters, underscores are not allowed, and the first letter must be lowercase. the first letter of each subsequent word must be capitalized
5. attribute names are only allowed to consist of letters, and underscores are not allowed...
6. for access to object members, we the "get" and "set" methods must always be used
7. when a class member method is declared as private, it must start with a double underscore "__"; when it is declared as protected, it must start with a single underscore" _"; member attributes declared as public are not allowed to contain underscores at any time.
8. if we need to define some frequently used methods as global functions, they should be defined in the class in static form
9. naming of functions using lowercase letters and underscores should clearly describe what the function does.
10.boolean values ??and null values ??are both lowercase.
11. when a string is composed of plain text (that is, it does not contain variables), it must always use single quotes (') as the delimiter
12. use when the array type declares an associative array, it should be divided into multiple lines to ensure that the keys and values ??of each line are aligned
13. all code in the class must be indented with four spaces
14. it is not allowed to use var to declare variables. class member variables must be declared as private, protected and public. usually get and set methods are used to access class members.
15. methods must always use private, protected or public to declare their scope
16. no extra spaces are allowed between the function or method name and the parameter brackets

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
