Basic knowledge of PHP Learning Notes _php Foundation

Source: Internet
Author: User
Tags arrays constant function definition http request lowercase session id php code alphanumeric characters

PHP learning so far more than a year, the accumulation of a lot of notes, but also quite miscellaneous, write an article to tidy up.

PHP Base Section

PHPThe base instruction for output text: echo and print .

The difference between Echo and print

echois a PHP statement, print and print_r is a function, the statement does not return a value, the function can have a return value (even if it is not used)

echoOutputs one or more strings.
printcan only print out values for simple type variables (such as int,string)
print_rYou can print out values for complex type variables (such as arrays, objects)

The difference between Var_dump and Print_r

var_dumpReturns the type and value of an expression and print_r returns only the result, which is easier to read than debugging code var_dump .

Variable

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

PHP has three different scope of variables:

local(局部)
global(全局)
static(静态)

Variables declared outside of a function have Global scope and can only be accessed outside of a function.

Variables declared within a function have LOCAL scope and can only be accessed within a function.

globalKeywords are used to access global variables within a function.

PHP Static Keywords

Typically, all variables are deleted when the function completes/executes. However, sometimes I need not delete a local variable. Achieving this requires further work.

To do this, use the static keyword when you first declare a variable:


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

PHP type

Boolean type

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

Integral type

We can use (int) to convert a decimal force type to an integer.

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

Array

There are three types of arrays in PHP:

索引数组:就是下标是顺序整数作为作为索引(比如第几排第几列)$class[5]
关联数组:就是下标是字符串作为索引(比如名字)$class2["zhangsan"]
多维数组 - 包含一个或多个数组的数组

The subscript is either an integer or a string.

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);
// 自 PHP 5.4 起
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

Array cells can be array[key] accessed through syntax.
Note: This does not mean always to enclose the key name. You do not need to enclose the key names as constants or variables, otherwise PHP you cannot parse them.

Array operator Example name result $a + $b Union $a and $b combined $a = = $b equal if $a and $b have the same key/value pair then true$a = = $b congruent if $a and $b have the same key/value pairs and the order and type are all The same is true$a!= $b unequal if $a is not equal to $b true$a <> $b Unequal if $a is not equal to $b true$a!== $b is not congruent if $a is not all equal to $b true

+operator appends the array element on the right to the left array, and the key names in each of the two arrays are ignored only in the left array and the right ones.

Object

To initialize an object, use the new statement to instantiate the object into 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:

Define Constants Examples:

<?php
define("poems" , "Homeric epic");

?>

PHP string Operators

In PHP, there is only one string operator.
(.)the concatenation operator is used to concatenate two string values. Such as:echo "a= ".$a."<br>";
to the left, the string literal "a=" is concatenated with the value of the variable $a, and the second is connected to a newline character "<br>"

PHP functions

A function is executed only when it is called, as in JS, and the function definition starts with the functions keyword.

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

When there is no return statement, the admiral will become " -2+10=";

Process Control

Here, just talk about the next foreach statement.

foreachStatement traversal output Array:
Grammar:

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

Parameter array_expression is the array that specifies the arrays to traverse, and the $value value of the array

<?php
     $actors [0] ="Marry";
     $actors [1] ="Lorry";
     $actors [2] = "mike";
     foreach ($actors as $values){

}
?>

The above code will output:
Name:marry
Name:lorry
Name:mike

Two important magic methods.

    1. __set( )方法:这个方法用来为私有成员属性设置值的,有两个参数,第一个参数为你  要为设置值的属性名,第二个参数是要给属性设置的值,没有返回值。
    2. __get()方法:这个方法用来获取私有成员属性值的,有一个参数,参数传入你要获取的成员属性的名称,返回获取的属性值,这个方法不用我们手工的去调用

Methods in PHP are case-insensitive

require(dirname(__FILE__).'/global.php'); //引入全局文件
require(dirname(__FILE__).'/config.ini.php'); //引入基本配置文件

Object operators and double colon operators

In a member method of a class, you can access non-static properties by using the-> (object operator), $this->property which is the property name.
Static properties are used :: (double colons): self::$property to access.

=> and->

=> array member access symbol, -> object member access symbol;
- > $name = $value : The current class's The value of the font face= "neo-Arial" >name variable is set to ;
represents the class itself, -> is an operator accessing its class members
Double colon operator ( ) class name static Properties/Methods
Font face= "neo-Arial":: used to invoke static properties and methods in a class

include(): contains an external file with the syntax format include (string filename);
require(): Output error message, terminate script
include_once(): When you call the same file multiple times, the program will only call once
require_once(): First check if the file has been invoked elsewhere
array_pop(): Gets and returns the last element in the array
count(): Count the number of elements in an array
array_search(): Gets the key name of the element in the array
$array_keys(): Gets all the key names of the repeating elements in the array

Single and double quotes

PHP treats the data in single quotes as a normal string and no longer handles it. and double quotes have to handle the strings.

Get and Post

$_get[] and $_post[] global arrays, which are used to receive the data that the get and POST methods pass to the current page, respectively. "[]" Inside is name.

PHP parameters to pass commonly used methods are 3: $_post[], $_get[], $_session[], respectively, to get the form, URL and Session variable values.

The difference between get and post in form submission is summed up in the following ways:

GET是从服务器上获取数据,POST是向服务器传送数据。
GET 是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。POST是通过HTTP POST机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。
对于GET方式,服务器端用Request.QueryString获取变量的值,对于POST方式,服务器端用Request.Form获取提交的数据。
GET传送的数据量较小,不能大于2KB(这主要是因为受URL长度限制)。POST传送的数据量较大,一般被默认为不受限制。但理论上,限制取决于服务器的处理能力。
GET 安全性较低,POST安全性较高。因为GET在传输过程,数据被放在请求的URL中,而如今现有的很多服务器、代理服务器或者用户代理都会将请求URL记 录到日志文件中,然后放在某个地方,这样就可能会有一些隐私的信息被第三方看到。另外,用户也可以在浏览器上直接看到提交的数据,一些系统内部消息将会一 同显示在用户面前。POST的所有操作对用户来说都是不可见的。

When a form is submitted, if method is not specified, the default is GET request (. NET defaults to post), and the data submitted in the form is appended to the URL to separate it from the URL. Alphanumeric characters are sent as is, but spaces are converted to "+", and other symbols are converted to%XX, where XX is the ASCII (or ISO Latin-1) value that the symbol is in 16. A GET request requests that the data submitted be placed in the HTTP request protocol header, while the data submitted by the post is placed in the Entity data, and the Get method submits data with a maximum of 2048 bytes and the post does not have this limit. The parameters of the post pass are in doc, the text that is passed on the HTTP protocol, and then the parameter part is parsed. Get the parameters. Generally use post is better. Post submission data is implicit, get is passed through the URL to pass some data that does not need to be classified, get is passed in the URL of the parameter, post is not.

1.GET the requested data is appended to the URL (that is, the data is placed in the HTTP protocol header) to split the URL and transmit the data, and the parameters are connected by &

2.GET way to submit data can only be 1024 bytes, theoretically post is not limited, can transmit a larger amount of data, IIS4 the largest 80kb,iis5 in the 100KB

HTTP status Code

Cookie and Session Difference

The contents of the cookie mainly include: name, value, expiration time, path and domain. A path, together with a domain, forms the scope of the cookie. If you do not set an expiration time, it indicates that this
The lifetime of a cookie is the time of the browser session, the cookie disappears when the browser window is closed. This lifetime is known as a session cookie for a browser session-time cookie.
Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated by the specification. If the expiration time is set, the browser will put the cookie
Save to your hard disk, and then open the browser again after closing, and the cookies will still be valid until you exceed the expiration time you set.

When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID
(called the session ID), if already included, the server retrieves the session by the session ID, if it has previously created a session for this client
Used (not retrieved, a new one is created), if the client request does not contain a session ID, create a session for the client and generate a session
The value of the associated session Id,session ID should be a string that is neither duplicated nor easily found to mimic, and this session ID will be in this response
is returned to the client for saving. The way to save this session ID is to use a cookie so that the browser can automatically send the logo to the following rules in the interactive process
Server.
1, the cookie data stored in the customer's browser, session data on the server.
2, cookies are not very safe, others can analyze stored in the local cookies and cookie spoofing
Consider that security should use session.
3, session will be stored in a certain period of time on the server. When the visit increases, it will take up the performance of your server
Consider the use of cookies for mitigating server performance.
4, a single cookie can not save more than 4K of data, many browsers limit a site to save up to 20 cookies.
5, so personal recommendations:
Storing important information such as login information as session
Additional information, if required, can be placed in a cookie

PHP Code specification

1. Variable assignment must remain equal spacing and arrangement

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

3. Ensure that file naming and invocation is consistent, due to the Unix-like system, which is sensitive to case

4. Method name only allowed by the letter, the underscore is not allowed, the first letter to lowercase, and then each word first letter to capitalize

5. The name of the attribute is only allowed to be composed of letters, underlining is not allowed ...

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

7. When a class member method is declared private, it must begin with a double underscore "__", must start with a single underline "_" when declared as protected, and a member property declared public is not allowed to have an underscore at any time.

8. If we need to define some commonly used methods as global functions, then they should be defined in a static (static) Form in the class

9. The name of the function uses lowercase and underscore, should be able to describe the function of the functions clearly.

Both the 10.Boolean value and the null value are lowercase.

11. When a string is composed of plain text (that is, it does not contain a variable), you must always use single quotes (') as delimiters

12. When declaring an associative array using the array type, you should divide it into multiple lines to ensure that the key and value of each row are aligned

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

14. Var is not allowed to declare variables, class member variables must be declared with private,protected and public. Class members are usually accessed using the get and set methods.

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

16. No extra spaces are allowed between the function or method name and the 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.