Variables and constants

Source: Internet
Author: User
Basics of variables and constant variables

Variables in PHP are represented by a dollar sign followed by the variable name. Variable names are case sensitive and Chinese characters may also be valid.

By default, values are always assigned. PHP also provides another way to assign values to variables: assign values to references. This means that the new variable simply references the original variable (in other words, "become its alias" or "point. Changing new variables will affect the original variables, and vice versa. Assign values by reference. simply add an & symbol to the variable to be assigned (source variable ). Note: only variables with names can reference values.

Predefined variables

PHP has a large number of predefined variables, and many variables depend on the server. some predefined variables do not take effect when running in the form of command lines.

PHP provides an additional set of pre-defined arrays. These array variables contain data from the web server (if available), runtime environment, and user input, which is usually called autoglobals) or superglobals ).

Variable range

The variable range here refers to the context defined by it, that is, its effective range. The scope of the variable contains the files introduced by include and require.

The global variables in PHP are a little different from those in C. in C, global variables automatically take effect in functions unless they are overwritten by local variables. Global variables in PHP must be declared as global when used in functions.

   

B. inc:

  

The program can output hello normally, but the annotated test () cannot be parsed normally, because the variable $ a is undefined.

Use global variables

If you want to use global variables in a function, you can use the following two methods.

  • Global keyword

  • global $a, $b;

    After a global variable is declared in a function, all references to any variable will point to its global version.

  • $ GLOBALS ultra-global variable array

  • $GLOBALS['b'] = $GLOBALS['a'] + $BLOBALS['b'];

    The usage is similar to that of the global keyword.

    Static variables

    Static variables only exist in local function domains, but their values are not lost when the program runs out of this scope. In addition, it is initialized only once during Declaration. The value of a static function is not overwritten when a function is called each time.

    If a value is assigned to a static variable in the declaration result, the parsing error is caused. the static declaration is parsed during compilation.

        

    Similar to the C language static, the following C code can also be set to 0 ~ Output 10 numbers in sequence.

    #include 
       
        void test(void) {    static int cnt = 0;    printf("%d ", cnt);    cnt++;    if(cnt < 10) {        test();    }    cnt--;}int main(void) {    test();    return 0;}
       

    Static and global definitions of variables are implemented by reference.

    Variable

    Variable variables are a special usage in the PHP language and do not exist in other languages.

    In short, a variable is a variable that obtains the value of a common variable as the variable name of the variable.

         

    When variables are used in arrays, ambiguity may occur. For example, if you write $ a [1], the compiler will report an error. the meaning you want to express must be replaced by the following two methods.

    $ {$ A [1]}
    $ A [1] as a variable

    $ {$ A} [1]
    $ A acts as a variable and retrieves the value of index 1 in the variable.

    Form variables

    When a form is submitted to a PHP script, the information in the form is automatically available in the script and can be accessed through $ _ GET [], $ _ POST [], and $ _ REQUEST.

    Note: the points and spaces in the variable name are converted into underscores. For exampleChanged to $ _ REQUEST ["a_ B"]. the following example shows the use of identifiers in the form.

      

    Process. php.

          

    Because the period is not a valid character in the PHP variable name, the output result is as follows.

    boolean falseboolean falseboolean truestring 'h3' (length=2)

    The magic_quotes_gpc configuration command affects the value of get/post/cooie. this feature has been removed and the single quotation marks, double quotation marks, backslash, and NULL characters in the input are not escaped. If you need to escape, you can use addslashes (). If you need to reference a referenced string, you need to use stripslashes ().

    PHP also understands arrays in the context of Form variables. the following example uses more complex form variables, post the form to itself, and display data when submitting the form.

           

    Be especially careful when heredoc contains Complex Variables. the above code $ _ SERVER ['php _ SELF '] without curly braces will report an error during running.

    Array (size = 4) 'personal' => array (size = 2) 'name' => string 'hello' (length = 5) 'detail' => string 'World' (length = 5) 'option' => array (size = 2) 0 => string 'A' (length = 1) 1 => string 'C' (length = 1) 'action' => string 'submitted' (length = 9) 'submit '=> string 'submit query content' (length = 12)
    IMAGE submission

    When submitting a form, you can use an image instead of the standard submit button. It's amazing to use it for the first time.

            

    For the above program, when a user clicks an image somewhere, the form will be transmitted to the server, and two variables sub_x and sub_y will be added, including the coordinates of the user clicking the image.

    array (size=3)  'action' => string '1' (length=1)  'sub_x' => string '334' (length=3)  'sub_y' => string '282' (length=3)
    Cookies

    PHP can use the setcookie () function to set cookies. cookies are part of the HTTP header and must be called before sending any output to the browser.

    The usage of cookies is as follows.

             

    Cookie data is available in the corresponding cookie array. if you assign multiple values to a cookie variable, you must assign it to an array.

    Constant syntax

    The value of a constant cannot be changed during script execution. Constants are case sensitive. Traditionally, constant identifiers are always uppercase. Once defined, a constant cannot be redefined or undefined. the constant value can only be a scalar.

    You can use the define () function to define constants, or use the const keyword to define constants outside the class definition. Custom constants do not start with Double underscores and may conflict with magic constants.

    define('FOO', 'something');const FOO = 'something';

    The use of the const keyword to define a constant must be at the top of the function region, because this method is defined during compilation. The range of constants is global. you can access constants anywhere in the script without having to worry about the zone.

    Magic constant

    The Magic constant value can be changed, but it is not a constant.

    _ LINE _ // The current row number in the FILE _ // the complete path and FILE name of the FILE, and the absolute path _ DIR _ // directory where the FILE is located, except for the root directory, the end slash is not included. it is equivalent to dirname (_ FILE _) _ FUNCTION _ // FUNCTION name, case-sensitive _ CLASS _ // CLASS name, including the declared region _ TRAIT _ // Trait name, including the declared NAMESPACE _ METHOD _ // METHOD name of the class _ NAMESPACE _ // name of the current NAMESPACE

    PHP provides a large number of predefined constants to any script it runs. the values of the above eight magic constants change as they change their position in the code.

    (Full text)

    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.