Basic php learning notes: php learning notes

Source: Internet
Author: User
Tags html header php basics

Basic php learning notes: php learning notes

I have been studying php for more than a year, and I have accumulated a lot of notes. I 'd like to write an article.

Php Basics

PHPBasic command for output text:echoAndprint.

Differences between echo and print

echoIs a PHP statement,printAndprint_rYes. The statement does not return values. The function can return values (even if it is not used)

echoOutput one or more strings.
printOnly values of simple type variables (such as int and string) can be printed)
print_rYou can print values of complex types of variables (such as arrays and objects)

Differences between var_dump and print_r

var_dumpReturns the type and value of the expression, whileprint_rReturns only results, compared to debugging codevar_dumpIt is easier to read.

Variable

Variables are used to store values, such as numbers, text strings, or arrays. All variables in PHP start with the $ symbol.
PHP variable names are case sensitive!

PHP has three different variable scopes:

Local)
Global)
Static)

Variables declared outside the function haveGlobalScope, which can only be accessed outside the function.

The variables declared in the function haveLOCALScope, which can only be accessed within the function.

globalKeyword is used to access global variables in a function.

PHP static keywords

Generally, when the function is completed/executed, all variables are deleted. However, sometimes I do not need to delete a local variable. Further work is required to achieve this.

To accomplish this, use the static keyword when declaring the variable for the first time:

<?php    
function myTest() {
   static $x=-1;
   echo $x;
   $x--;
}
myTest();//-1
echo "<br>";
myTest();//-2
echo "<br>";
myTest();//-3
?>

Php type

Php type: ** PHP supports eight primitive types. **

Boolean

To specify a Boolean value, use the keyword TRUE or FALSE. Both are case insensitive.

Integer

We can use (int) to forcibly convert decimals to integers.

<?php
    var_dump((int)(26/3));//int(8)
?>

Array

Php has three Arrays:

Index Array: The subscript is an ordered Integer as an index (for example, the number of rows in the row) $ class [5]
Associated array: The subscript is a string as an index (for example, name) $ class2 ["zhangsan"]
Multi-dimensional array-an array containing one or more Arrays

The subscript must be an integer or a string.

<? Php
$ Array = array (
"Foo" => "bar ",
"Bar" => "foo ",
);
// From PHP 5.4
$ Array = [
"Foo" => "bar ",
"Bar" => "foo ",
];
?>

The array unit can bearray[key]Syntax.
Note: This does not mean that the key name is always enclosed in quotation marks. You do not need to quote a key named constant or variable. OtherwisePHPThey cannot be parsed.

Array OperatorsExampleNameResult $ a + $ B Union $ a and $ B Union $ a ==$ B equal if $ a and $ B have the same key/value pair, TRUE $ a = ==$ B. If $ a and $ B have the same key/value pairs and the order and type are the same, TRUE $! = $ B. If $ a is not equal to $ B, the value is TRUE $ a <> $ B. If $ a is not equal to $ B, the value is TRUE $! = $ B incomplete. If $ a is not complete, $ B is TRUE.

+The operator attaches the array element on the right to the back of the array on the left, and the key names in both arrays are used only in the array on the left, and the elements on the right are ignored.

Object

To initialize an object, use the new statement to instance the object to a variable.

Common 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.

Constant

You can use the define () function to define constants. Once a constant is defined, it cannot be changed or undefined.
Common magic constants:

Example of defining constants:

<?php
define("poems" , "Homeric epic");
echo poems ;//outputs "Homeric epic"
?>

Php string Operator

In PHP, there is only one string operator.
Concatenation operator(.)Concatenates two string values. For example:echo "a= ".$a."<br>";
Connect the string "a =" to the value of the variable $ a on the left, and the second is the line break."<br>"Connection

Php Functions

The function is executed only when it is called. This is the same as JavaScript. Similarly, the function definition starts with the function keyword.

<?php
    function sum($x,$y){
        $z=$x + $y;
        return $z;
    }
    echo "-2+10= ".sum(-2,10);//outputs "-2+10=8"
?>

When noreturnStatement, the above will become "-2 + 10 = ";

Process Control

Here, I will only talk aboutforeachStatement.

foreachStatement to traverse the output array:
Syntax:

foreach (array_expression as $value){ statement};foreach (array_expression as $key => $value){ statement};

Parametersarray_expressionIs the array to be traversed,$valueIs the value of the array

<?php
     $actors [0] ="Marry";
     $actors [1] ="Lorry";
     $actors [2] = "mike";
     foreach ($actors as $values){
     echo "Name:$values<br>";
}
?>

The above code will be output:
Name: Marry
Name: Lorry
Name: mike

Two important magic methods

1. _ set () method: This method is used to set values for private member attributes. There are two parameters. The first parameter is the attribute name for the set value, the second parameter is the value to be set for the attribute, with no return value. 2. _ get (): This method is used to obtain the attribute value of a private member. There is a parameter that is used to input the name of the member attribute you want to obtain and return the obtained attribute value, this method does not need to be manually called.

Methods in php are case insensitive.

Require (dirname (_ FILE __). '/global. php '); // introduce the Global FILE require (dirname (_ FILE __). '/config. ini. php '); // introduce the basic configuration file

Object operator and double colon Operator

In the member methods of the class, you can use the-> (Object operator ):$this->property(Property is the property name) to access non-static properties.
Static attributes are used::(Double colon ):self::$property.

=> And->

=>Array member access symbol,->Object member access symbol;
$this->$name=$value:nameSet the variable value$value;
$thisRepresents the class itself,->Is the operator used to access its class members.
Double colon operator (::) Class Name::Static attributes/methods
"::"Is used to call static attributes and methods in the class.

include(): Contains external files. The syntax format is include (string filename );
require(): Will output the error message, terminate the script
include_once(): When the same file is called multiple times, the program will only call once
require_once(): First, check whether the file has been called elsewhere.
array_pop(): Get and return the last element in the array
count(): Count the number of elements in the array
array_search(): Get the key name of the element in the array
$array_keys(): Get all key names of repeated elements in the array

Single quotation marks and double quotation marks

PHP treats the data in single quotes as a normal string and does not process it any more. Double quotation marks also process the strings.

Get and post

$ _ GET [] and $ _ POST [] global arrays: they are used to receive the data transmitted to the current page by the GET and POST methods, respectively. "[]" Contains name.

There are three common methods for passing php parameters: $ _ POST [], $ _ GET [], and $ _ SESSION [], which are used to obtain the values of form, URL, and Session variables respectively.

The differences between get and post methods in Form submission are summarized as follows:

GET gets data from the server, and POST transfers data to the server.
GET adds the parameter data queue to the URL referred to by the ACTION attribute of the submission form. The values correspond to each field in the form one by one and can be seen in the URL. POST uses the http post mechanism to place fields in the form and their content in the html header and send them to the URL address referred to by the ACTION attribute. You cannot see this process.
For the GET method, the server uses Request. QueryString to obtain the value of the variable. For the POST method, the server uses Request. Form to obtain the submitted data.
The size of data transmitted by GET is small and cannot exceed 2 kb (this is mainly because the URL length is limited ). The amount of data transmitted by POST is large, which is generally not restricted by default. However, theoretically, the limit depends on the server's processing capability.
GET is less secure and POST is more secure. Because GET data is stored in the request URL during transmission, many existing servers, proxy servers, or user proxies record the request URL to the log file, and put it somewhere, so that some private information may be seen by a third party. In addition, you can also directly view the submitted data in the browser, and some internal messages of the system will be displayed in front of the user. All POST operations are invisible to users.

If Method is not specified during FORM submission, the default value is GET request (. net is POST by default). The data submitted in Form will be appended to the url? Separated from the url. The letter and number characters are sent as they are, but spaces are converted to "+". Other symbols are converted to % XX, XX represents the ASCII (or ISO Latin-1) value in hexadecimal notation. The data to be submitted for the GET request is placed in the HTTP Request Header, while the data to be submitted by POST is placed in the object data. The data to be submitted by the GET method can contain up to 2048 bytes, POST does not have this restriction. The parameters passed by POST are in the doc, that is, the text transmitted by the http protocol. When accepted, the parameter section is parsed. Obtain parameters. Generally, it is better to use POST. The data submitted by POST is implicit. GET is passed in the url to pass some data that does not need to be kept confidential. GET is passed through parameters in the URL, and POST is not.

1. The GET request data will be appended to the URL (that is, the data is placed in the HTTP header? Splits the URL and transmits data. parameters are connected with each other

2. The data submitted in GET mode can only be 1024 bytes at most. Theoretically, there is no limit on POST. A large amount of data can be transferred. The maximum size of IIS4 is 80 KB, and that of IIS5 is kb.

HTTP status code

Differences between cookie and session

Cookie content mainly includes: name, value, expiration time, path and domain. The path and the domain form the scope of the cookie. If the expiration time is not set,
The life cycle of each cookie is the browser session. When the browser window is closed, the cookie disappears. This cookie is called a session cookie.
Session cookies are generally stored in the memory instead of on the hard disk. Of course, this behavior is not standardized. If the expiration time is set, the browser will set the cookie
Save it to the hard disk, close it, and open the browser again. These cookies are still valid until the specified expiration time is exceeded.

When the program needs to create a session for a client request, the server first checks whether the client request contains a session ID.
(Called session id). if it already exists, it indicates that a session has been created for this client before, and the server retrieves the session according to the session id.
If the client request does not contain the session id, a session is created for the client and
The associated session id. The value of the session id should be a string that is neither duplicated nor easily found to be counterfeited. This session id will be returned in this response.
. The cookie can be used to save the session id. In this way, the browser can automatically send the id
Server.
1. cookie data is stored in the client's browser, and session data is stored on the server.
2. Cookies are not safe. Others can analyze the Cookies stored locally and perform cookie spoofing.
Session should be used for security consideration.
3. The session will be stored on the server for a certain period of time. When the number of accesses increases, it will occupy the performance of your server.
COOKIE should be used in consideration of reducing server performance.
4. data stored in a single cookie cannot exceed 4 kb. Many browsers limit that a site can store up to 20 cookies.
5. Personal suggestions:
Store important information such as login information as SESSION
Other information can be stored in the COOKIE if it needs to be retained.

Php code specification

1. Variable assignments must be equal to spacing and Arrangement

2. No extra spaces are allowed at the end of each line.

3. Ensure that the file name is the same as the call case, because the file name is case sensitive on Unix-like systems.

4. The method name can only consist of letters. The underline is not allowed. The first letter must be in lower case, and the last letter of each word must be in upper case.

5. the attribute name can only consist of letters, and the underline is not allowed.

6. For access to object members, we must always use the "get" and "set" methods.

7. when the class member method is declared as private, it must begin with a double underline "_"; when it is declared as protected, it must begin with a single underline; the member attribute declared as public cannot contain underscores at any time.

8. If we need to define some frequently used methods as global functions, we should define them in the class in static form.

9. The name of the function should be in lower case and underline, so that you can clearly describe the function of the function.

10. Both Boolean and null values are in lower case.

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. When the array type is used to declare the joined array, it should be divided into multiple rows to ensure the alignment of keys and values in each row

13. All code in the class must be indented with four spaces

14. Variables cannot be declared using var. class member variables must be declared using private, protected, and public. The get and set methods are usually used to sort class members.

15. The method must always use private, protected, or public to declare its scope.

16. Unnecessary spaces are not allowed between the function or method name and parameter brackets.

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.