PHP05 PHP Language Basics

Source: Internet
Author: User
Tags arithmetic operators array definition bitwise bitwise operators natural logarithm pear value of pi variable scope

Learning Essentials
    • Initial knowledge of PHP
    • Basic syntax
    • Variable
    • Constant
    • Operator
    • An expression

Learning Goals
    • Mastering PHP Basic Syntax
    • Mastering PHP variables
    • Mastering PHP Constants
    • Mastering PHP expressions
    • Mastering PHP Operators

The first PHP program of PHP

    • Writing code

1. Write the code in Notepad and save it as hello.php.

2. Save files in D:\wamp\www directory

3, IE Address bar access: http://localhost:80/hello.php

    • Attention points

1. All PHP code begins with <?php and ends with ?> (can be omitted).

2. Echo is the statement that PHP uses to output a string. "Echo-output one or more strings";

    • Echo is a language structure and not a function, so it cannot be called by a variable function.
    • Multiple arguments, you cannot use parentheses. Use the "." Connection.
    • Format:void Echo (String $arg 1 [, String $ ...])

3. Each statement ends with a ";" sign. > Implicit semicolon, so the last sentence specifies that ";" may not be used.

4. The file suffix must end in PHP. When we call the hello.php file to the server, the server will automatically send the PHP suffix file to the PHP function module processing, the processing results are returned to the client browser.

PHP Processing HTML Forms
    • Writing code

Form page code:

    <fieldset>       <legend> User Information </legend>       <form action= "d02action.php" method= "POST" >           <p>              <label for= "UserName" > Name:</label>              <input type= "text" name= "UserName" id= " UserName ">           </p>           <p>              <label for=" userlocal "> from:</label>              <input type = "text" name= "userlocal" id= "userlocal" >           </p>           <p>              <input type= "Submit" value= "Submit" >               <input type= "reset"  value= "reset" >           </p>       </form>    </fieldset>

Form Processing page code:

Hello everyone, my name is: <?php echo $_post[' userName '];? ><br> I come from: <?php echo $_post[' userlocal '];? >

    • Attention points

1. You must run form pages and form processing pages in a server environment.

2, $_post is the global variable of PHP, all the data submitted by post are stored in this variable.

3, PHP processing multi-marquee checkbox involves the concept of PHP array, follow-up course explanation.

Practice PHP Processing form data on the computer

Base syntax php delimiter

Because PHP is an embedded scripting language, you need some kind of markup to isolate the PHP code from the HTML code, which is the PHP delimiter:

    • <?php PHP code ?> //xml style, standard usage, recommended use
    • <script language= "php" > PHP code </script> //Long style tags
    • <? PHP code ?> //Short style tag, need to open in php.ini Short_open_tag
    • <% PHP code %> //asp style tag, need to open in php.ini asp_tags

The server-side PHP parser parses the code in the delimiter, and the code outside the delimiter is ignored. The complete HTML page is returned to the client browser after parsing is complete.

PHP comments
    • Single-line Comment
    • #号单行注释
    • /**/Multi-line comments
    • /**

*phpdocumentor comments. The Phpdocumentor tool can automatically generate code for code comments.

*/

  Example:

<?phpecho "line 1th PHP code <br>";//single line comment//echo "2nd line PHP code <br>";//Code comment echo "3rd line PHP code <br>";/** Multiline Comment @param Meaning */echo "line 4th PHP code <br>";/* multi-line Comment */echo "5th line PHP code <br>"; #单行注释echo "6th line PHP code <br>"; echo "7th Line PHP code < Br> ";? >

  

White space character processing

Whitespace: Spaces, tab tabs, line breaks

    • Use two blank lines in the following cases

1. A source file between two code fragments.

2. Between declarations of two classes.

    • Use a blank line for the following situations

1. Between two function declarations.

2. Between the local variables within the function and the first statement of the function.

3. Block comments or line comments before.

4. Between two logical code segments within a function.

    • The rules for the use of spaces can be reduced by code to improve readability

1. Spaces are generally applied between keywords and parentheses. Note: The function name and the opening parenthesis should not be separated by a space.

2. Insert a space after the comma in the function's argument list.

3. A space should be added between the operand of the mathematical formula and the operator (except for binary operations and unary operations).

Expressions in 4.for statements should be separated by commas, followed by spaces.

5. The closing parenthesis of a forced type in a type conversion statement must be separated from the expression with a comma, and a space should be added.

PHP Data type

PHP is a weakly typed language, and the data type of a variable does not have to be specified by the developer, but rather is determined by the context of the program's execution to determine the data type of the variable.

The data types of PHP variables can be divided into:

    • Scalar types: integer type, floating-point type, String type, Boolean type.
    • Composite type: Array type and object type.
    • Special type: Resource, NULL
    • Pseudo type: Mixed,number,callback

If you want to see the value and type of an expression, you can use the function var_dump ().

1. Integral type: integer

$i = 123;//decimal Integer $i = -123;//Specifies a negative number $i = 076;//Specifies an octal number $i = 0x7a;//Specifies a hexadecimal digit

  

2. Floating-point type: float

Two forms of representation

$f = 1.23; $f = 1.23e3;//1.23*10*10*10=1230$f = 1.23e-3;//1.23/1000=0.00123

  

3. String Type: String    

$s = "php string", or $s = ' php string ';

The difference between a single quote and a double-quoted string:

    • If there are variables in a double-quoted string, the variable is replaced by the actual value. Explicitly represents a variable in a string: ${var} or {$var}.
    • The single-quote string does not replace the variable character, nor does it escape characters other than "\" and "'". PHP efficiently handles strings and is recommended for use.

Delimiter definition string (Cannot initialize class member):

$string =<<<str delimiter .....        STR; Echo  $string;

The variables in the delimiter are also parsed. Typically used to output large pieces of text from a file or database. You don't usually need to use escape characters, but you can also use them in double quotes.

Escape characters and descriptions in PHP:

special characters

meaning

\r

specify carriage return symbol

\n

specify line break symbols

\ T

specify tabs

< P align= "Center" >\\

specify \

\$

Specify dollar sign

\ "

specify "Number

The string connection in PHP takes "." No.: $str 1. $str 2.

4. Boolean Type: Boolean

$flag = true; $falg = False;//true or FALSE values are case-insensitive; True is 1,false 0

  

5. Array type: arrays

PHP Array Definition:

$arr = Array ("Spring", "Summer", "Fall", "Winter");

Access the array, accessed by subscript (also known as: Index, key):

echo  $arr [1];

Another way of accessing an array, accessed through a string index (also known as an associative array access):

Array definition: Key

$arr = Array ("sp" = "Spring", "su" = "Summer", "fa" = "Fall", "wi" = "Winter");

  

Access: $arr ["SP"]

6. Type: Object

Consists of a set of property values and a set of methods.

<?phpclass person{  var  $name;  function say () {     echo "My name is:". $this->name;  }} $p =new person (); $p->name= "Tom"; $p->say ();? >

  

7. Resource type: Resource

A resource is a special type of variable that maintains a reference to an external resource. Established and used by specialized functions, including: Opening files, database connections, graphics canvas area, etc. special handles, created, used and released by programmers. The system has a garbage collection mechanism. The Free-result function is used to manually release resources.

The following statement returns a resource reference if the resource was created successfully, otherwise false.

<?php//file Resource $file_handle=fopen ("Info.txt", "W"), Var_dump ($file _handle);//Output resource (3, Stream)//directory Resource $dir_ Handle=opendir ("c:\\windows\\fonts"); Var_dump ($dir _handle);//Output resource (4, stream)//Database connection resource $link_mysql=mysqli_ Connect ("localhost", "root", "rootkit"); Var_dump ($link _mysql);//Output object (MYSQLI) [1] ...//artboard resource $img_handle= Imagecreate (+), Var_dump ($img _handle);//Output resource (6, GD)//xml Parser Resource $xml_parser=xml_parser_create (); var_ Dump ($xml _parser);//Output resource (7, XML)?>

  

8.NULL type

Indicates that a variable has no value. Does not represent spaces, 0, and empty strings. Indicates that the value of a variable is null.

Null value for the case:

    • Assigns the value of the variable directly to NULL.
    • The declared variable has not been assigned a value.
    • The variable that is destroyed by the unset () function.
    • Empty ($var):
BOOL Empty (mixed $var)

  

If var is a non-null or nonzero value, empty () returns FALSE. In other words,"",0,"0",NULL,FALSE,Array (),var $var; and objects that do not have any properties will be considered empty and return TRUEif var is empty.

Example:

<?php$a=null; $b = "Tom"; unset ($b); Var_dump ($a);//Output Nullvar_dump ($b);//Output Nullvar_dump ($c);//Output null?>

  

9. Pseudo-Class Introduction

It is used primarily in the parameters of a function to receive multiple types of data, even other functions as callback functions.

Mixed: A parameter can accept many different types.

Number: A parameter can be either an integer or a float.

Callback: Can be a custom function or built-in function, or an object's method as a parameter. Except for array (), Echo (), Empty (), eval (), exit (), Isset (), list (), print (), unset ().

On-machine Exercise 2 Output Merchandise shopping list

PHP Data type conversions

Data type conversions are divided into: coercion type conversions and automatic type conversions.

PHP is a weakly typed variable, so the type of the variable is automatically converted by default.

    • Automatic type conversion

Scalar participates in automatic type conversions. Note: Type conversions do not change the type of the operand itself, but only how these operands are evaluated.

Boolean,null,string,integer conversion to Integer for calculation

Boolean,null,string,integer,float conversion to float for calculation

Boolean conversion to 0 or 1

Null conversion to 0

Convert integer to float

String conversion: 123abc to 123;123.14abc converted to 123.14.

<?php$var= "100page", $var +=2; $var = $var +1.3; $var =null+ "Pices Paper"; $var =5+ "10.123 yuan";? >

  

    • Forcing type conversions

1, bracket coercion type conversion

(int), (integer)

(bool), (Boolean)

(float), (double), (real)

(string)

(array)

(object)

2. Function type Conversion

Intval ()

Floatval ()

Strval ()

3, the above two types of conversions do not change the type of the variable itself, but the new type is assigned to the new variable for calculation. If you want to change, use the Settype () function to set the type of the variable.

For example:

$var = "Ture"; Settype ($var, "string");

  

    • Type conversion Details

1. Integer to floating point number, the accuracy is unchanged.

2. Floating point number to Integer, automatically discard fractional part. Ensure that the range of floating-point numbers does not exceed the integer range, otherwise the result is indeterminate.

3.Null is converted to a string, the null character "".

Declaration of variable variables

A variable is an address alias that stores data in memory.

The declaration of a variable must begin with the $ symbol followed by the variable name, using " =" to assign a value to the variable.

Scope of variable: function local variable scope inside function. If it is not a function internal variable, the scope is used between the beginning and end of the PHP tag and all open PHP tags in the page, as well as in the files introduced by include and require. If you place a variable in a cookie or session, multiple pages can access the variable.

Common variables Test function:

Unset (): Releases the specified variable

Isset (): Detects if the variable is set

Empty (): detects if a variable is empty

For example:

$var = "; Empty ($var); Isset ($var); Unset ($var);

It is recommended to use!empty ($var) to determine if a variable exists and cannot be empty.

Name of the variable

Strictly case-sensitive. However, built-in structures, built-in functions, custom functions, and keywords are not case-sensitive.

Variable name specification:

Start with a character or underscore, followed by any number of letters, numbers, or underscores. There can be no spaces or dots in the middle. The law of Camel Nomenclature.

Variable variable

Dynamic settings and variable names that change variables.

For example:

$hi = "Hello"; $ $hi = "PHP";  $ $hi equivalent to $hello

  

Assigning a reference to a variable

Variables are always assigned values. Meaning that two variables are assigned to each other, changing the value of one of the variables will not affect the value of the other variable, and the value of the two variables is duplicated.

Reference assignment: All variables point to the same numeric value. Change the value and change the value of all variables. Use the & symbol.

For example:

$foo = ' Bob '; $bar =& $foo;

  

$bar = ' My name is Tom ';//What is the value of $foo now?

differs from C language &. The C language & represents a variable as a common body. PHP does not cause the common body, but only the respective values associated together . Using Uset () does not cause all reference variables to disappear.

Test functions for variable types

Var_dump (): View the value and type of an expression

Gettype (): Determines the variable type return type name.

Returns TRUE or FALSE for the Is_type function.

    • Is_bool (): Determines whether it is a Boolean type
    • Is_int (), Is_integer (), Is_long (): Determine whether the integer type
    • Is_float (), is_double (), Is_real (): Determines whether it is a floating-point type
    • Is_string (): Determine if it is a string
    • Is_array (): Determines whether an array
    • Is_object (): Determines whether an object
    • Is_resource (): Determines whether the resource type
    • Is_null (): Determines whether it is empty
    • Is_scalar (): Determines whether it is a scalar
    • Is_numeric (): Determines whether it is any type of numeric or numeric string
    • Is_callable (): Determines whether the function name is valid.

Constant

Used for fixed values in data calculation, once defined, the amount of the program cannot be changed during the run. is generally global scope. Variable data can only be declared as constants.

    • Definition and Declaration

Define (string name,mixed value [, bool case_insensitive]);//define a constant function

First parameter: constant name, no $ symbol required

Second parameter: Constant value

Third argument: If true, the constants are case-insensitive and, if false, differentiated.

    • The difference between a constant and a variable

1. No dollar sign ($) before constant

2. Constants can only be defined with the Define () function, not through assignment statements

3. Constants can be defined and accessed anywhere without regard to the rules of variable scope

4. Constants cannot be redefined or undefined once defined

5. The value of a constant can only be scalar

    • System pre-defined constants

1. Kernel predefined constants: Constants that are defined in the kernel of PHP. is case sensitive.

2.php_version: Returns the version of PHP.

3.php_os: Returns the name of the operating system executing the PHP interpreter.

4.php_eol: System line break, Windows is (\ r \ n), Linux is (\ n), Mac is (\ r).

    • Standard predefined constants: Constants defined by PHP by default. is case sensitive.

M_PI: Returns the value of Pi Pi.

For example:

<?php Echo ' php common predefined constants '. '  <br><br> '; Echo ' Current PHP version is (php_version): '. Php_version. '   <br><br> '; Echo ' is currently using the operating system type (Php_os): '. Php_os. '   <br><br> '; The interface between the Echo ' Web server and PHP is (PHP_SAPI): '. Php_sapi. '   <br><br><br> '; Echo ' Maximum number of integers (Php_int_max): '. Php_int_max. '   <br><br> '; echo ' PHP default include path (Default_include_path): '. Default_include_path. '   <br><br> '; The installation path of Echo ' PEAR (pear_install_dir): '.   Pear_install_dir. ' <br><br> '; echo ' PEAR extension Path (pear_extension_dir): '.   Pear_extension_dir. ' <br><br> '; echo ' PHP execution Path (php_bindir): '. Php_bindir. '   <br><br> '; The path to the Echo ' PHP extension module is (php_libdir): '. Php_libdir. '   <br><br> '; Echo ' points to the nearest error place (E_error): '. E_error. '   <br><br> '; Echo ' points to the nearest warning point (e_warning): '. E_warning. '   <br><br> '; Echo ' points to the nearest note (E_notice): '. E_notice. '   <br><br> '; echo ' Natural logarithm E value (m_e): '.   M_e. ' <br><br> '; echo ' Mathematical value of Pi (M_PI): '. M_pi. ' <br><br>‘; echo ' Logical Truth (TRUE): '. TRUE. '   <br><br> '; Echo ' Logical false Value (FALSE): '. FALSE. '   <br><br> '; Echo ' Current file lines (__line__): '. __line__. ' <br><br> '; is a two underscore echo ' current file Pathname (__file__): '. __file__. '  <br><br> '; Echo ' <br> '. The currently called function name (__function__): '. __function__. '   <br><br> '; echo ' class name (__class__): '. __class__. '   <br><br> '; Echo ' class method name (__method__): '. __method__. ' <br><br> ';? >

    • Magic Constants

Values change depending on where they are used.

    • __LINE__: Returns the current line number in the file. Can also be written as __line__.
    • __FILE__: Returns the absolute path (including the file name) of the current file.
    • __DIR__: Returns the absolute path (without the file name) of the current file, equivalent to DirName (__file__).
    • __FUNCTION__: Returns the name of the current function (or method).
    • __CLASS__: Returns the current class name (including the scope or namespace of the class).
    • __TRAIT__: Returns the current TRAIT name (including the scope or namespace of the TRAIT).
    • __METHOD__: Returns the current method name (including the class name).
    • __NAMESPACE__: Returns the name of the namespace for the current file.
Operators are categorized by operand

Unary operator:!true//operator + operand

Binary operators: $a + $b//operand + operator + operand

Ternary operator: true?1:0; Expression + operator + expression + operator + expression

Classification by function
    • Arithmetic operators

Note: Also ++,--, increment decrement operator

    • String operators

    • Assignment operators

The PHP assignment operator is used to write values to variables.

The base assignment operator in PHP is "=". This means that the right-hand assignment expression sets the value for the left-hand operand.

    • Comparison operators

A PHP comparison operator is used to compare two values (numbers or strings):

    • logical operators

    • Bitwise operators

Bitwise operators allow you to evaluate and manipulate the bits specified in the integer number.

Displacement is a mathematical operation in PHP. Bits that are moved in any direction are discarded. The right side of the left shift is filled with 0, and the sign bit is removed, which means the signs are not retained. When you move right, the left side is filled with a symbol bit, which means the sign is retained.

Use parentheses to ensure that you want the priority. For example $a & $b = = True to first compare and then bitwise AND ($a & $b) = = True to first bitwise and then compare.

    • Array operators

    • Other operators

1. Ternary operator: (? :)

2. Execute operator: (') anti-quote. Indicates that the content inside is executed as an operating system command and returns its output information. The effect is the same as the function shell_exec (). To maintain cross-platform, use functions as much as possible.

3. Error control: Used to mask error messages generated by an expression. Always put in--if you can get a value somewhere, just precede him with the @ sign. For example: @ $sum =100/0;

    • Operator Precedence

Exercise 3: Enter a 5-digit number to calculate the sum of your numbers

Tip: Form input number, processing the page processing number and output.

An expression

An expression is a combination of variables, constants, and operational symbols.

    • The most basic expressions are constants and variables: $a =5
    • A slightly more complex expression is a function: $a =func ();
    • Increment-Decrement expression: $a + +,--$a;
    • Comparison expression: $a >5
    • Combination operation Assignment expression: $a +=5;
    • Ternary operation expression: $v = ($a? $b = 5: $c =10);

PHP05 PHP Language Basics

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.