立诚勿怠,格物致知
It's all about connecting the dots

Introduction to PHP

Source: Learning PHP, MySQL, JavaScript and CSS

Incorporating PHP within HTML

By default, PHP documents end with th extension .php. When a web server encounters this extension in a requested file, it automatically passes it to the PHP processor. Of course, web servers are highly configurable, and some web developers choose to force files ending with .htm and .html to also get parsed by the PHP processor, usually because they want to hide the fact that they are using PHP.

Your PHP program is responsible for passing back a clean file suitable for display in a web browser. At its very simplest, a PHP document will output only HTML. To prove this, you can take any normal HTML document, such as an index.html file, and save it as index.php; it will display identically to the original.

Calling the PHP parser

To trigger the PHP commands, use $lt;?php, and to close them, use ?>.

By the way, a slight variation to the PHP syntax exists. If you browse the Internet for PHP examples, you may also encounter code where the opening and closing syntax used is like this:



Although it’s not as obvious that the PHP parser is being called, this is a valid, alternative syntax that also usually works. However, it should be discouraged, as it is incompatible with XML and its use is now deprecated (meaning that it is no longer recommended and that support could be removed in future versions).

If you have only PHP code in a file, you may omit the closing ?>. This can be a good practice, as it will ensure you have no excess whitespace leaking from your PHP files (especially important when writing object-oriented code).

The structure of PHP

Using comments

There are two ways in which you can add comments to your PHP code. The first turns a single line into a comment by preceding it with a pair of forward slashes, like this:


    // This is a comment

This version of the comment feature is a great way to temporarily remove a line of code from a program that is giving you errors. For example, you could use such a comment to hide a debugging line of code until you need it, like this:


    // echo "X equals $x";

You can also use this type of comment directly after a line of code to describe its action, like this:


    $x += 10; // Increment $x by 10

When you need multiple-line comments, there’s a second type of comment, which looks like:


You can use the /* and */ pairs of characters to open and close comments almost anywhere you like inside your code. Most, if not all, programmers use this construct to temporarily comment out entire sections of code that do not work or that, for one reason or another, they do not wish to be interpreted.

Basic syntax

PHP is quite a simple language with roots in C and Perl, yet it looks more like Java. It is also very flexible, but there are a few rules that you need to learn about its syntax and structure.

Semicolons

PHP commands ended with a semicolon, like this:


    $x += 10;

Probably the most common cause of errors you will encounter with PHP is forgetting this semicolon, which causes PHP to treat multiple statements like one statement, which it is unable to understand. This leads to a "Parse error" message.

The $ symbol

The $ symbol has come to be used in many different ways by different programming languages. For example, if you have ever written in the BASIC language, you will have used the $ to terminate variable names to denote them as strings.

In PHP, however, you must place a $ in front of all variables. This is required to make the PHP parser faster, as it instantly knows whenever it comes across a variable. Whether your variables are numbers, strings, or arrays, they should all look something like those below:



And really, that's pretty much all the syntax that you have to remember. Unlike languages such as Python, which is very strict about how you indent and lay out our code, PHP leaves you completely free to use (or not use) all the indenting and spacing you like. In fact, sensible use of what is called whitespace is generally encouraged (along with comprehensive commenting) to help you understand your code when you come back to it. It also helps other programmers when they have to maintain your code.

Understanding variables

String variables, numeric variables and arrays...

Variable naming rules

When creating PHP variables, you must follow these four rules:

  • Variable names must start with a letter of the alphabet or the _ (underscore) character.
  • Variable names can contain only the characters a-z, A-Z, 0-9, and _ (underscore).
  • Variable names may not contain spaces. If a varialbe must comprise more than one word, the words should be separated with the _ (underscore) character (e.g., $user_name).
  • Variable names are case-sensitive. The variable $High_Score is not the same as the variable $high_score.

Operators

Operators are the mathematical, string, comparison, and logical commands such as plus, minus, times, and divide, which in PHP looks a lot like plain arithmetic; for instance, the following statements outputs 8:


    echo 6 + 2;

Before moving on to learn what PHP can do for you, take a moment to learn about the various operators it provides.

Arithmetic operators

Operator Description Example
+ Addition $j+1
- Subtraction $j-6
* Multiplication $j*11
/ Division $j/4
% Modulus (division remainder) $j%9
++ Increment ++$j
−− Decrement −−$j

Assignment operators

Operator Example Equivalent to
= $j=15 $j = 15
+= $j+=5 $j = $j + 5
-= $j-=3 $j = $j - 3
*= $j*=8 $j = $j * 8
/= $j/=16 $j = $j / 16
.= $j.=$k $j = $j . $k
%= $j%=4 $j = $j % 4

Strings have their own operator, the period (.).

Comparison operators

Operator Description Example
== Is equal to $j == 4
!= Is not equal to $j != 21
> Is greater than &j > 3
< Is less than $j < 100
>= Is greater than or equal to $j >= 15
<= Is less than or equal to $j <= 8

Note the difference between = and ==. The first is an assignment operator, and the second is a comparison operator. Even more advanced programmers can sometimes transpose the two wen coding hurriedly, so be careful.

Logical operators

If you haven't used them before, logical operators may at first seem a little daunting. But just think of them the way would use logic in English. For example, you might say to yourself, "If the time is later than 12 PM and earlier than 2 PM, then have lunch." In PHP, the code for this might look something like the following (using military timing):


    If ($hour > 12 && $hour < 14) dolunch();

Here we have moved the set of instructions for actually going to lunch into a function that we will have to create later called dolunch(). The them of the statement is left out, because it is implied and therefore unnecessary.

As the previous example shows, you generally use a logical operator to combine the results of two of the comparison operators shown in the previous section. A logical operator can also be input to another logical operator ("If the time is later than 12 PM and earlier than 2 PM, or if the smell of a roast is permeating the hallway and there are plates on the table ..."). As a rule, if something has a TRUE or FALSE value, it can be input to a logical operator. A logical operator takes two true-or-false inputs and produces a true-or-false result.

Operator Description Example
&& And $j == 3 && $k == 2
and Low-precedence and $j == 3 and $k == 2
|| Or $j < 5 || $j > 10
or Low-precedence or $j < 5 or $j > 10
! Not !($j == $k)
xor Exclusive or $j xor $k

Note that && is usually interchangeable with and; the same is true for || and or. But and and or have a lower precedence, so in some cases, you may need extra parentheses to force the required precedence. On the other hand, there are times when only and or or is acceptable, as in the following statement, which uses an or operator:


    mysql_select_db($database) or die("Unable to select database");

The most unusual of these operators is xor, which stands for exclusive or and returns a TRUE value if either value is TRUE, but a FALSE value if both inputs are TRUE or both inputs are FALSE. To understand this, imagine that you want to concoct your own cleaner for household items. Ammonia makes a good cleaner, and so does bleach, so you want your cleaner to contain one of them. But the cleaner must not contain both, because the combination is hazardous. In PHP, you could represent this as:


    $ingredient = $ammonia xor $bleach;

In the example snippet, if either $ammonia or $bleach is TRUE, $ingredient will also be set to TRUE. But if both are TRUE or both are FALSE, $ingredient will be set to FALSE.

Variable assignment

The syntax to assign a value to a variable is always variable = value. Or, to reassign the value to another variable, it is other_variable = variable.

There are also a couple of other assignment operators that you will find useful. For example, we've already seen:


    $x += 10;

which tells the PHP parser to add the value on the right (in this instance, the value 10) to the variable $x. Likewise, we could subtract as follows:


    $y -+ 10;

Variable incrementing and decrementing

Adding or subtracting 1 is such a common operation that PHP provides special operators for these tasks. You can use one of the following in place of the += and -= operators:


    ++$x;
    --$y;

In conjunction with a test (an if statement), you could use the following code:


    if (++$x == 10) echo $x;

This tells PHP to first increment the value of $x and then test whether it has the value 10 and, if so, output its value. You can also require PHP to increment (or, in the following example, decrement) a variable after it has tested the value, like this:


    if ($y-- == 0) echo $y;

which gives a subtly different result. Suppose $y starts out as 0 before the statement is executed. The comparison will return a TRUE result, but $y will be set to -1 after the comparison is made. So what will the echo statement display: 0 or -1? Try to guess, and then try out the statement in a PHP processor to confirm. Because this combination of statements is confusing, it should be taken as just an educational example and not as a guide to good programming style.

In short, whether a variable is incremented or decremented before or after testing depends on whether the increment or decrement operator is placed before or after the variable.

By the way, the correct answer to the previous questions is that the echo statement will display the result -1, because $y was decremented right after it was accessed in the if statement, and before the echo statement.

String concatenation

String concatenation uses the period (.) operator to append one string of characters to anther. The simplest way to do this is as follows:


    echo "You have " . $msgs . " messages.";

Assuming that the variable $msgs is set to the value 5, the output from this line of code will be:


    You have 5 messages.

Just as you can add a value to a numeric variable with the =+ operator, you can append one string to another using .= operator like this:


    $bulletin .= $newsflash;

String types

PHP supports two types of strings that are denoted by the type of quotation mark that you use. If you wish to assign a literal string, preserving the exact contents, you should use the single quotation mark (apostrophe) like this:


    $info = 'Preface variables with a $ like this: $variable';

In this case, every character within the single-quoted string is assigned to $info. If you had used double quotes, PHP would have attempted to evaluate $variable as a variable. On the other hand, when you want to include the value of a variable inside a string, you do so by using a double-quoted string:


    echo "There have been $count presidents of the US";

As you will realize, this syntax also offers a simpler form of concatenation in which you don't need to use a period, or close and reopen quotes, to append one string to another. This is called variable substitution. You will notice some applications using it extensively and others not using it at all.

Escaping characters

Sometimes a string needs to contain characters with special meanings that might be interpreted incorrectly. For example, the following line of code will not work, because the second quotation mark (apostrophe) encountered in the word sister's will tell the PHP parser that the end of the string has been reached. Consequently, the rest of the line will be rejected as an error:


    $text = 'My sister's car is a Ford'; // Erroneous syntax

To correct this, you can add a backslash directly before the offending quotation mark to tell PHP to treat the character literally and not to interpret it:


    $text = 'My sister\'s car is a Ford';

You can perform this trick in almost all situations in which PHP would otherwise return an error by trying to interpret a special character. For example, the following double-quoted string will be correctly assigned:


    $text = "My mother always said \"Eat your greens\"."

Additionally, you can use escape characters to insert various special characters into string, such as tabs, newlines, and carriage returns. These are represented, as you might guess, by \t, \n and \r. Here is an example using tabs to lay out a heading; it is included here merely to illustrate escapes, because in web pages there are always better ways to do layout:


    $heading = "Date/tName/tPayment"'

These special backslash-preceded characters work only in double-quoted strings. In single-quoted strings, the preceding string would be displayed with the ugly \t sequences instead of tabs. Within single-quoted strings, only the escaped apostrophe (\') and the escaped backslash itself (\\) are recognized as escaped characters.

Multiple-line commands

There are times when you need to output quite a lot of text form PHP, and using several echo (or print) statements would be time-consuming and messy. To overcome this, PHP offers two conveniences. The first is just to put multiple lines between quotes. Variables can also be assigned.





PHP also offers a multiline sequence using the <<< operator, commonly referred to as here-document or heredoc for short. This is a way of specifying a string literal, preserving the line breaks and other whitespace (including indentation) in the text. Its use can be seen as below:



What this code does is tell PHP to output everything between the two _END tags as if it were a double-quoted string. This means it's possible, for example, for a developer to write entire sections of HTML directly into PHP code and then just replace specific dynamic parts with PHP variables.

It is important to remember that the closing _END; tag must appear right at the start of a new line and must be the only thing on that line -- not even a comment is allowed to be added after it (nor even a single space). Once you have closed a multiline block, you are free to sue the same tag name again.

Remember: using the <<<_END..._END; heredoc construct, you don't have to add \n line-feed characters to send a line feed -- just press Return and start a new line. Also, unlike either a double-quote- or single-quote-delimited string, you are free to use all the single and double quotes you like within a heredoc, without escaping them by preceding them with a backslash (\).

The example below shows how to use the same syntax to assign multiple lines to a variable.



The variable $out will then be populated with the contents between the two tags. If you were appending rather than assignment, you also could have used .= in place of = to append the string to $out.

Be careful not to place a semicolon directly after the first occurrence of _END, as that would terminate the multiline block before it had even started and cause a "Parse error" message. The only place for the semicolon is after the terminating _END tag, although it is safe to use semicolons within the block as the normal text characters.

By the way, the _END tag is simply one I chose for these examples because it is unlikely to be used anywhere else in PHP code. You can use any tag you like, such as _SECTION1, _OUTPUT, and so on. Also, to help differentiate tags such as this from variables or functions, the general practice is to preface them with an underscore, but you don't have to use one if you choose not to.

Laying out text over multiple lines is usually just a convenience to make your PHP code easier to read, because once it is displayed in a web page, HTML formatting rules take over and whitespace is suppressed (but $author is still replaced with the variable's value).

So, for example, if you load these multiline output examples into a browser they will not display over several lines, because all browsers treat newlines just like spaces. However, if you use the browser's view source feature, you will find that the newlines are correctly placed, and the output does appear over several lines.

Variable typing

PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.



At the point of the assignment, $number is a numeric variable. But on the second line, a call is placed to the PHP function substr, which asks for one character to be returned from $number, starting at the fourth position (remembering that PHP offsets start from zero). To do this, PHP turns $number into a nine-character string, so that substr can access it and return the character, which in the case is 1.

The following is an example automatically converting a string to a number.



Constants

Constants are similar to variables, holding information to be accessed later, except that they are what they sound like -- constant. In other words, once you have defined one, its value is set for the remainder of the program and cannot be altered.

One example of a use of a constant might be to hold the location of your server root (the folder containing the main files of your website). You would define such a constant like this:


    define("ROOT_LOCATION", "/usr/local/www/");

Then, to read the contents of the variable, you just refer to it like a regular variable (but it isn't preceded by a dollar sign):


    $directory = ROOT_LOCATION;

Now, whenever you need to run your PHP code on a different server with a different folder configuration, you have only a single line of code to change.

The main two things you have to remember about constants are that they must not be prefaced with a $ (as with regular variables), and that you can define them only using the define function.

It is generally agreed to be good practice to use only uppercase for constant variable names, especially if other people will also read your code.

Predefined constants

PHP comes ready-made with dozens of predefined constants that you generally will be unlikely to use as a beginner. However, there are a few, known as the magic constants, that you will find useful right from the start. The names of the magic constants always have two underscores at the beginning and two at the end, so that you won't accidentally try to name one of your own constants with a name that is already taken. They are detailed in the table below:

Magic constant Description
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. In PHP 4.0.2, __FILE__ always contains an absolute path with symbolic links resolved, whereas in older versions it might contain a relative path under some circumstances.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is he root directory. (Added in PHP 5.3.0).
__FUNCTION__ The function name. (Added in PHP 4.3.0.) As of PHP 5, returns the function name as it was declared (case-sensitive). In PHP 4, its value is always lowercase.
_CLASS__ The classname. (Added in PHP 4.3.0.) As of PHP 5, returns the class name as it was declared (case-sensitive). In PHP 4, its value is always lowercase.
__METHOD__ The class method name. (Added in PHP 5.0.0.) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__ The name of the current namespace (case-sensitive). This constant is defined at compile time. (Added in PHP 5.3.0.)

One handy use of these constants is for debugging purposes, when you need to insert a line of code to see whether the program flow reaches it:


    echo "This is line " . __LINE__ . " of file " . __FILE__;

This causes the current program line in the current file (including the path) being executed to be output to the web browser.

The difference between the echo and print commands

So far, you have seen the echo command used in a number of different ways to output text from the server to your browser. In some cases, a string literal has been output. In others, strings have first been concatenated or variables have been evaluated. I've also shown output spread over multiple lines.

But there is also an alternative to echo that you can use: print. The two commands are quite similar to each other, but print is an actual function that takes a single parameter, whereas echo is a PHP language construct.

By and large, the echo command will be a tad faster than print i general text output, because--not being a function--it does't set a return value.

On the other hand, because it isn't a function, echo cannot be used as part of a more complex expression, whereas print can. Here's an example to output whether the value of a variable is TRUE or FALSE using print--something you could not perform in the same manner with echo, because it would display a "Parse error" message:


    $b ? print "TRUE" : print "FALSE";

The question mark is simply a way of interrogating whether variable $b is TRUE or FALSE. Whichever command is on the left of the following colon is executed if $b is TRUE, whereas the command to the right is executed if $b is FALSE.

Generally, though, the examples in this book use echo, and I recommend that you do so as well until you reach such a point in your PHP development that you discover that need for using print.

Functions

Functions are used to separate out sections of code that performs a particular task. For example, maybe you often need to look up a date and return it in a certain format. That would be a good example to turn into a function. The code doing it might be only three lines long, but if you have to paste it into your program a dozen times, you're making your program unnecessarily large and complex, unless you use a function. And if you decide to change the data format later, putting it in a function means you'll have to change it in only one place.

Placing such code into a function not only shortens your source code and makes it more readable, it also adds extra functionality (pun intended), because functions can be passed parameters to make them perform differently. They can also return values to the calling code.

To create a function, declare it in the manner shown in the example below:



The function takes a Unix timestamp (an integer number representing a date and time based on the number of seconds since 00:00 AM on January 1 1970) as its input and then calls the PHP date function with the correct format string to return a date in the format Monday August 1st 2016. Any number of parameters can be passed between the initial parentheses; we have chosen to accept just one. The curly braces enclose all the code that is executed when you later call the function.

To output today's date using this function, place the following call in your code:


    echo longdate(time());

This call uses the built-in PHP time function to fetch the current Unix timestamp and passes it to the new longdate function, which then returns the appropriate string to the echo commend for display. If you need to print out the date 17 days ago, you now just have to issue the following call:


    echo longdate(time()-17*24*60*60);

which passes to longdate the current Unix timestamp less the number of seconds since 17 days ago (17 days x 24 hours x 60 minutes x 60 seconds).

Functions can also accept multiple parameters and return multiple results.

Variable scope

If you have a very long program, it's quite possible that you could start to run out of good variable names, but with PHP you can decide the scope of a variable. In other words, you can, for example, tell it that you want the variable $temp to be used only inside a particular function and to forget it was ever used to when the function returns. In fact, this is the default scope for PHP variables.

Alternatively, you could inform PHP that a variable is global in scope and thus can be accessed by every other part of your program.

Local variables

Local variables are variables that are created within, and can be accessed only by, a function. They are generally temporary variables that are used to store partially processed results prior to the function's return.

One set of local variables is the list of arguments to a function. In the previous section, we defined a function that accepted a parameter named $timestamp. This is meaningful only in the body of the function; you can't get or set its value outside the function.

For another example of a local variable, take another look at the longdate function, which is modified slightly in the example below:



Here we have assigned the value returned by the date function to the temporary variable $temp, which is then inserted into the string returned by the function. As soon as the function returns, the value of $temp is cleared, as if it had never been used at all.

Now, to see the effects of variable scope, let's look at some similar code in the example below. Here, $temp has been created before calling the longdate function.



Because $temp was neither created within the longdate function nor passed to it as a parameter, longdate cannot access it. Therefore, this code snippet only outputs the date and not the preceding text. In fact, it will first display the error message "Notice: Undefined variable: temp."

The reason for this is that, by default, variables created within a function are local to that function and variables created outside of any function can be accessed only by nonfunction code.

Some ways to repair the above example in the following examples.



The above example moves the reference to $temp out of the function. The reference appears in the same scope where the variable was defined.


$temp = "The date is ";
echo longdate($temp, time());

function longdate($text, $timestamp)
{
    return $text . date("l F jS Y", $timestamp);
}
?>

The solution in the above example passes $temp to the longdate function as an extra argument. longdate reads it into a temporary variable that it creates called $text and outputs the desired result.

Forgetting the scope of a variable is a common programming error, so remembering how variable scope works will help you debug some quite obscure problems. Suffice it to say that unless you have declared a variable otherwise, its scope is limited to being local: either to the current function or to the code outside of any functions, depending on whether it was first created or accessed inside or outside a function.

Global variables

There are cases when you need a variable to have global scope, because you want all your code to be able to access it. Also, some data may be large and complex, and you don't want to keep passing it as arguments to functions.

To declare a variable as having global scope, use the keyword global. Let's assume that you have a way of logging your suers into your website and you want all your code to know whether it is interacting with a logged-in user or a guest.

Static variables

Superglobal variables

Superglobals and security

赞(0) 打赏
文章名称:《Introduction to PHP》
文章链接:https://www.orzzone.com/introduction-to-php.html
商业联系:yakima.public@gmail.com

本站大部分文章为原创或编译而来,对于本站版权文章,未经许可不得用于商业目的,非商业性转载请以链接形式标注原文出处。
本站内容仅供个人学习交流,不做为任何投资、建议的参考依据,因此产生的问题需自行承担。

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力提供更多优质内容!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册