PHP Basic tutorial Six functions, constants

Source: Internet
Author: User

What this section explains

    • Include and include_once

    • Require and require_once

    • Constant

    • Introduction of file and constant combination case columns

    • Variable manipulation functions

    • Output statement

Objective

In the previous article, we discussed the application of functions, but only in a file to call the function, when we want to make a function call in different files, the contents of the above section can not be implemented, but the PHP language provides the introduction of the concept. Let the problem be solved perfectly.

References to files

If a file, such as the a.php file, is going to use the function of the b.php file, it is necessary for us to introduce the functions in the B file into the a file. PHP bit we provide four ways to achieve the goal, namely include, include_once, require, require_once.

There are four ways to do this, but each one is different in the way it is introduced.

Include and include_once

As you can see from the name, both of these introductions have include, and the two common features are that when the file is introduced in error (because you can't guarantee that every file introduced is correct) it won't terminate the program, but it will go on.

<?php    include ' a.php ';    The file that was introduced by Echo ' was wrong ';

Results:

Include

Include, a form of introduction to a file, has two features:

    1. When an include file is faulted, the program does not stop immediately and it continues to execute.

    2. If the file has been introduced, it will be introduced repeatedly,

The first feature has been discussed above, the second feature, when repeated in the code using the include introduction of the same file, it will be introduced repeatedly.

<?php/** * a.php The contents of the file, a sum function */function sum ($a, $b) {    return $a + $b;} Contents of the func.php file <?php    include ' a.php ';    Include ' a.php ';    Echo ' Duplicate introduction of file ';

Results:

As you can see in this case with include it will be an error, meaning that you have introduced the file before, can not be introduced again.

Include_once

Include_once It is much like the include, in addition to the introduction of errors will continue to execute, but also when the file has been introduced, it will not be introduced again.

<?php    include_once ' a.php ';    Include_once ' a.php ';    Echo ' introduces a file once. ';..... Results...... Introduce a file once.

You can see that the above code does not have an error.

Require and require_once

Require and require_once are another way to introduce files. Their common features are:

When a file is introduced with an error, it terminates the program and does not execute down.

<?php    require ' b.php ';    Echo ' That sentence will not be executed ';

Results:

Require

Require, a form of introduction to a file, has two features:

    1. When the file introduced by require is wrong, the program stops immediately.

    2. If the file has been introduced, it will be introduced repeatedly,

The first feature has been discussed above, and the second feature, when repeated in code using require to introduce the same file, it will be introduced repeatedly.

<?php/** * a.php The contents of the file, a sum function */function sum ($a, $b) {    return $a + $b;} Contents of the func.php file <?php    require ' a.php ';    Require ' a.php ';    Echo ' introduces a file once. ';

Results:

In the above can be seen at this time with require it will error, meaning that you have introduced the file before, can not be introduced again.

Require_once

Require_once It is similar to require, except that the introduction of an error terminates the program, and that it will not be introduced again after the file has been introduced.

<?php    require_once ' a.php ';    Require_once ' a.php ';    Echo ' introduces a file once. ';..... Results...... Introduce a file once.

You can see that the above code does not have an error.

The system provides us with four ways, but how do we know what kind of introduction to choose?

If we are introducing some files (such as getting a database connection, opening a file, etc.) It is recommended to use _once this way to introduce files to prevent waste of resources. And we often use require and require_once this way in development.

It is more recommended to use require_once this way. Because you can save resources by using this approach, you can avoid repeating the definition of errors that occur.

File introduction mechanism

In-depth understanding of the introduction of the file: in PHP when the introduction of another file in a file, the introduction of the file will be executed, we can return a value in the introduced file, or do not return until the end of the file.

<?php    Echo ' This is the introduction of File <br> ';    Require_once ' b.php '; Introduce b file    Echo ' Execute this sentence after the introduction of the file <br> '; b.php file <?php    echo ' This is another file <br> ';    Return, ... Results...... This is the file that was introduced. This is another file. Execute this sentence after the introduction of the file is executed

Looking closely at the code above, you can see that using the return termination statement in the introduced file does not terminate the primary file. Although they run in the same memory, they do not affect their own operation.

Return problem with file introduction

A total of three points are summed up in the question of return:

    • When we introduce a file, the default is to successfully return 1

    • We can also return data based on the actual situation, such as an array.

    • During the introduction of a file, when the return statement of the file being introduced is encountered, the ingestion process terminates, returning the main file and continuing execution.

Constant

In our development process, often need some global values, is determined and we will not modify them in the future, such as the root directory path of the site, we have not been able to use variables, because variables we can be modified. Here we introduce another type of constant in PHP;

Constants : Constants can be understood as a special variable that, once defined, cannot be changed or de-defined [i.e.: cannot unset constants].

So what do we use to define constants? There are two methods available in PHP to define constants.

    • Define (string $name, constant value); Define a constant

      1. The first parameter is our constant name.

      2. The second parameter is the value of a constant, and only scalar and null are allowed. The scalar type is an integer, float, String, or Boolean. It is also possible to define a constant value of type resource, but it is not recommended to do so, which can lead to the occurrence of an unknown condition.

    • Const after PHP 5.3.0, you can use the Const keyword to define constants outside of the class definition.

Both of these can be used when we define constants.

<?php    define (' PI ', 3.1415926);    Echo PI. ' <br> ';    Const TAX = 0.012;    echo tax;    ...... The result ...    3.1415926    0.012

From the code above you can see that the definition of constants and variables are different, and they are two different.

the difference between a constant and a variable :

    1. The constant is preceded by a dollar sign ($);

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

    3. Constants can be defined and accessed anywhere, regardless of the scope of the variable;

    4. Once a constant is defined, it cannot be redefined or undefined;

    5. The value of a constant can only be scalar.

    6. The names of constants are generally capitalized.

In addition to our own defined constants, the PHP system also defines constants for us, such as the php_int_max we use when we are talking about integers, to get the maximum value of an integer type.

Magic Constants

PHP language can be said to have a feature, its syntax has the concept of magic. In system constants There is the concept of magic, PHP called Magic constants, what is the magic constant?

Magic constants: PHP provides a large number of predefined constants to any script it runs. However, many constants are defined by different extensions, and are only present when the extensions are loaded, either dynamically after loading, or they are included at compile time. (A large pile of words-_-not understand);

In a nutshell , the system provides a total of eight magic constants whose values change as they change position in the code. For example, the value of __line__ depends on the row it is in the script to determine. These special constants are case insensitive.

The Magic constants of PHP:

    1. The current line number in the __line__ file.

    2. The full path and file name of the __file__ file. If used in the included file, returns the file name that is included. From PHP 4.0.2, __file__ always contains an absolute path (if it is a symbolic connection, the resolved absolute path), and the previous version sometimes contains a relative path.

    3. The directory where the __dir__ file resides. If used in the included file, returns the directory where the included files are located. It is equivalent to DirName (__file__). Unless it is a root directory, the name in the directory does not include the trailing slash. (New in PHP 5.3.0) =

    4. __function__ function name (PHP 4.3.0 new addition). From PHP 5 This constant returns the name (case-sensitive) when the function is defined. In PHP 4, this value is always in lowercase letters.

    5. The name of the __class__ class (PHP 4.3.0 new addition). From PHP 5 This constant returns the name of the class when it is defined (case-sensitive). In PHP 4, this value is always in lowercase letters. The class name includes its declared action area (for example, Foo\bar). Note since PHP 5.4, __CLASS__ has also worked for trait. When used in the trait method, __class__ is the name of the class that invokes the trait method.

    6. __trait__ TRAIT's name (PHP 5.4.0 new addition). From PHP 5.4 This constant returns the name of the trait when it is defined (case-sensitive). The Trait name includes its declared function area (for example, Foo\bar).

    7. The method name of the __method__ class (PHP 5.0.0 new addition). Returns the name of the method when it is defined (case-sensitive).

    8. __NAMESPACE__ the name of the current namespace (case sensitive). This constant is defined at compile time (PHP 5.3.0 is new).

Example:

<?php    define (' PI ', 3.1415926);    Echo PI. ' <br> ';    Const TAX = 0.012;    Echo Tax. ' <br> ';    Echo __dir__; Use magic constants to get the absolute path where the current file is located.    ...... The result ...    3.1415926    0.012    D:\mywamp\Apache24\htdocs\zendstudio\yunsuanfu

You can see that when you use the magic constant of __dir__, the absolute path of the file is obtained automatically after running.

The above content is the use of constants, of course, more practice. How do we use magic constants and files to introduce development in development?

Best examples of introducing files and Magic constants

In the development of our introduction of files, the path of the file is a key, we have two options, one is a relative path, one is an absolute path. In development we often choose absolute path, that is, the path of the file, such as c:/mywamp/apache24/..., this format can be understood as an absolute path.

Here we take a comprehensive application of the introduction of files and Magic constants:

In the folder above that we might use in development, today we are simply using, that is, the process behind

    • There are some F function files under the Lib folder, which have functions we use, which we can define as function.php

    • Use magic constants in Lib's init.php to define constants that represent the absolute path of a file, even if you change the path of the project, and you can also introduce a function library in init.php

    • Introduce the init.php file in index.php.

function.php:

<?php    function Getsum ($a, $b) {//calculates two number of and        return $a + $b;    }    function getsub ($a, $b) {//calculates the difference of two numbers        return $a-$b;    }

init.php

<?php    //define the project's root directory    define (' Web_root_path ', DirName (__dir__). '/');    Defines the path of the CSS    define ("Css_path", Web_root_path. ' css/');    Defines the path of JS    define (' Js_path ', Web_root_path. ' js/');    Defines the path to the picture    define (' Image_path ', Web_root_path. ' image/');    Defines the path that holds the template    define (' Template_path ', Web_root_path. ' template/');    Defines the path of the LIB    define (' Lib_path ', Web_root_path. ' lib/');    Defines the path of the MODEL    define (' Model_path ', Web_root_path. ' model/');    We use the absolute path of LIB to introduce the function.php file    require Lib_path. ' function.php ';

In Init we use the magic constant __dir__ to dynamically get the directory where the file is located, and then through DirName () (the description gives a string containing a full path to a file, this function returns the directory name after removing the file name), the root directory of the project, Then the absolute path of each folder is obtained according to the root directory, and the function file is introduced by absolute path at last.

index.php

<?php    require_once './lib/init.php ';//Here you get the initialization file by relative path    //The above representation has introduced the initialization file, and we introduced the function file in the initialization. So you can use the function in the function file directly here.    $sum = getsum (10,23);    $sub = Getsub (10,5);    echo $sum;    Echo ' <br> ';    echo $sub;    ...... The result ...    5

Can be seen in the index.php file can normally use the function file under the Lib function.

The above is the most basic use of the introduction of files and Magic constants.

End of function

Through the above introduction, the basic introduction of the use of the function and the use of constants, the completion of the function, we have to review the past do not know.

Functions for manipulating variables

    • Isset (): Detects whether a variable is set, undefined, or null when a false value is returned

    • Unset (): destroys the specified variable. You can pass in a variable in the function to destroy it.

    • Empty (): Determines whether a variable is considered empty. When a variable does not exist, or its value is equal to FALSE, it is considered non-existent.

    • Is_int (): Is series has a number of functions to determine the type of a variable, such as Is_int, when the variable is of type integer, returns True, otherwise false.

PHP Output statements

Echo

Echo is actually not a function, it is a PHP statement, so you can not apply parentheses later, when you want to use echo to output more than the time, you can use commas separated. Echo does not return a value.

Print

Print is the same as echo usage, but echo is faster than print and print is not a function, it has a return worth, always returns 1.

Print_r

Print_r (variable) prints easy-to-understand information about variables. If the variable is string,integer,float it will output its value directly, and if the variable is an array, it will output a formatted array.

Printf

The printf function returns a formatted string whose syntax is

printf (FORMAT,ARG1,ARG2)

Var_dump

Var_dump () Generally we are output variables of the contents, types and strings of the content, type, length, so we can see what the type of the variable is.

Summarize

Through these two sections, the knowledge of functions and constants is finished, the function of the call process and operation in the future development we must be clear on the chest.

The above is the PHP Basic tutorial six function, constant content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

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