CHAPTER 2 – PHP 5 Basic Language

PHP 5 Basic Language "A language that doesn't have everything is actually easier to program in than some that do."--Dennis M. Ritchie 2.1 INTRODUCTION PHP borrows a bit of its syntax from other languages such as C, shell, Perl, and even Java. It is really a hybrid language, taking the best features from other languages and creating an easy-to-use and powerful scripting language. When you finish reading this chapter, you will have learned The basic language structure of PHP How PHP is embedded in HTML How to write comments Managing variables and basic data types Defining constants for simple values The most common control structures, most of which are available in other programming languages Built-in or user-defined functions If you are an experienced PHP 4 developer, you might want to skip to the next chapter, which covers object-oriented support of the language that has changed significantly in PHP 5.

2.2 HTML EMBEDDING The first thing you need to learn about PHP is how it is embedded in HTML: <HTML> <HEAD>Sample PHP Script</HEAD> <BODY> The following prints "Hello, World": <?php print "Hello, World"; ?> </BODY> </HTML> In this example, you see that your PHP code sits embedded in your HTML. Every time the PHP interpreter reaches a PHP open tag <?php, it runs the enclosed code up to the delimiting ?> marker. PHP then replaces that PHP code with its output (if there is any) while any non-PHP text (such as HTML) is passed through as-is to the web client. Thus, running the mentioned script would lead to the following output: <HTML> <HEAD>Sample PHP Script</HEAD> <BODY> The following prints "Hello, World": Hello, World </BODY> </HTML> Tip: You may also use a shorter <? as the PHP open tag if you enable the short_open_tags INI option; however, this usage is not recommended and is therefore off by default. Because the next three chapters deal with language features, the examples are usually not enclosed inside PHP open and close tags. If you want to run them successfully, you need to add them by yourself. 2.3 COMMENTS The next thing you need to learn about PHP is how to write comments, because most of the examples of this chapter have comments in them. You can write comments three different ways:

2.4 VARIABLES Variables in PHP are quite different from compiled languages such as C and Java. This is because their weakly typed nature, which in short means you don't need to declare variables before using them, you don't need to declare their type and, as a result, a variable can change the type of its value as much as you want. Variables in PHP are preceded with a $ sign, and similar to most modern languages, they can start with a letter (A-Za-z) or _ (underscore) and can then contain as many alphanumeric characters and underscores as you like. Examples of legal variable names include $count $_Obj $A123 Example of illegal variable names include $123 $*ABC As previously mentioned, you don't need to declare variables or their type before using them in PHP. The following code example uses variables: $PI = 3.14; $radius = 5; $circumference = $PI * 2 * $radius; // Circumference = * d You can see that none of the variables are declared before they are used. Also, the fact that $PI is a floating-point number, and $radius (an integer) is not declared before they are initialized. PHP does not support global variables like many other programming languages (except for some special pre-defined variables, which we discuss later). Variables are local to their scope, and if created in a function, they are only available for the lifetime of the function. Variables that are created in the main script (not within a function) aren't global variables; you cannot see them inside functions, but you can access them by using a special array $GLOBALS[], using the variable's name as the string offset. The previous example can be rewritten the following way: $PI = 3.14; $radius = 5; $circumference = $GLOBALS["PI"] * 2 * $GLOBALS["radius"]; // Circumference = * d You might have realized that even though all this code is in the main scope (we didn't make use of functions), you are still free to use $GLOBALS[], although in this case, it gives you no advantage. 2.4.1 Indirect References to Variables An extremely useful feature of PHP is that you can access variables by using indirect references, or to put it simply, you can create and access variables by name at runtime. Consider the following example: $name = "John"; $$name = "Registered user"; print $John; This code results in the printing of "Registered user." The bold line uses an additional $ to access the variable with name speci- fied by the value of $name ("John") and changing its value to "Registered user". Therefore, a variable called $John is created. You can use as many levels of indirections as you want by adding addi- tional $ signs in front of a variable. 2.4.2 Managing Variables Three language constructs are used to manage variables. They enable you to check if certain variables exist, remove variables, and check variables' truth values. 2.4.2.1 isset() isset() determines whether a certain variable has already been declared by PHP. It returns a boolean value true if the variable has already been set, and false otherwise, or if the variable is set to the value NULL. Consider the following script: if (isset($first_name)) { print '$first_name is set'; } This code snippet checks whether the variable $first_name is defined. If $first_name is defined, isset() returns true, which will display '$first_name is set.' If it isn't, no output is generated. isset() can also be used on array elements (discussed in a later section) and object properties. Here are examples for the relevant syntax, which you can refer to later: Checking an array element: if (isset($arr["offset"])) { ... } Checking an object property: if (isset($obj->property)) { ... } Note that in both examples, we didn't check if $arr or $obj are set (before we checked the offset or property, respectively). The isset() construct returns false automatically if they are not set. isset() is the only one of the three language constructs that accepts an arbitrary amount of parameters. Its accurate prototype is as follows: isset($var1, $var2, $var3, ...); It only returns true if all the variables have been defined; otherwise, it returns false. This is useful when you want to check if the required input vari- ables for your script have really been sent by the client, saving you a series of single isset() checks. 2.4.2.2 unset() unset() "undeclares" a previously set variable, and frees any memory that was used by it if no other variable references its value. A call to isset() on a variable that has been unset() returns false. For example: $name = "John Doe"; unset($name); if (isset($name)) { print '$name is set'; } This example will not generate any output, because isset() returns false. unset() can also be used on array elements and object properties similar to isset().

2.4.2.3 empty() empty() may be used to check if a variable has not been declared or its value is false. This language construct is usually used to check if a form variable has not been sent or does not contain data. When checking a variable's truth value, its value is first converted to a Boolean according to the rules in the following section, and then it is checked for true/false. For example: if (empty($name)) { print 'Error: Forgot to specify a value for $name'; } This code prints an error message if $name doesn't contain a value that evaluates to true. 2.4.3 Superglobals As a general rule, PHP does not support global variables (variables that can automatically be accessed from any scope). However, certain special internal variables behave like global variables similar to other languages. These vari- ables are called superglobals and are predefined by PHP for you to use. Some examples of these superglobals are $_GET[]. An array that includes all the GET variables that PHP received from the client browser. $_POST[]. An array that includes all the POST variables that PHP received from the client browser. $_COOKIE[]. An array that includes all the cookies that PHP received from the client browser. $_ENV[]. An array with the environment variables. $_SERVER[]. An array with the values of the web-server variables. These superglobals and others are detailed in Chapter 5, "How to Write a Web Application with PHP." On a language level, it is important to know that you can access these variables anywhere in your script whether function, method, or global scope. You don't have to use the $GLOBALS[] array, which allows for accessing global variables without having to predeclare them or using the deprecated globals keyword. 2.5 BASIC DATA TYPES Eight different data types exist in PHP, five of which are scalar and each of the remaining three has its own uniqueness. The previously discussed variables can contain values of any of these data types without explicitly declaring their type. The variable "behaves" according to the data type it contains.

2.5.1 Integers Integers are whole numbers and are equivalent in range as your C compiler's long value. On many common machines, such as Intel Pentiums, that means a 32-bit signed integer with a range between ­2,147,483,648 to +2,147,483,647. Integers can be written in decimal, hexadecimal (prefixed with 0x), and octal notation (prefixed with 0), and can include +/- signs. Some examples of integers include 240000 0xABCD 007 -100 Note: As integers are signed, the right shift operator in PHP always does a signed shift. 2.5.2 Floating-Point Numbers Floating-point numbers (also known as real numbers) represent real numbers and are equivalent to your platform C compiler's double data type. On common platforms, the data type size is 8 bytes and it has a range of approximately 2.2E­308 to 1.8E+308. Floating-point numbers include a deci- mal point and can include a +/- sign and an exponent value. Examples of floating-point numbers include 3.14 +0.9e-2 -170000.5 54.6E42 2.5.3 Strings Strings in PHP are a sequence of characters that are always internally null- terminated. However, unlike some other languages, such as C, PHP does not rely on the terminating null to calculate a string's length, but remembers its length internally. This allows for easy handling of binary data in PHP--for example, creating an image on-the-fly and outputting it to the browser. The maximum length of strings varies according to the platform and C compiler, but you can expect it to support at least 2GB. Don't write programs that test this limit because you're likely to first reach your memory limit. When writing string values in your source code, you can use double quotes ("), single quotes (') or here-docs to delimit them. Each method is explained in this section.

2.5.3.1 Double Quotes Examples for double quotes: "PHP: Hypertext Pre-processor" "GET / HTTP/1.0n" "1234567890" Strings can contain pretty much all characters. Some characters can't be written as is, however, and require special notation: n Newline. t Tab. " Double quote. \ Backslash. ASCII 0 (null). r Line feed. $ Escape $ sign so that it is not treated as a variable but as the character $. {Octal #} The character represented by the specified octal #--for exam- ple, 70 represents the letter 8. x{Hexadecimal #} The character represented by the specified hexadecimal #--for example, x32 represents the letter 2. An additional feature of double-quoted strings is that certain notations of variables and expressions can be embedded directly within them. Without going into specifics, here are some examples of legal strings that embed vari- ables. The references to variables are automatically replaced with the vari- ables' values, and if the values aren't strings, they are converted to their corresponding string representations (for example, the integer 123 would be first converted to the string "123"). "The result is $resultn" "The array offset $i contains $arr[$i]" In cases, where you'd like to concatenate strings with values (such as vari- ables and expressions) and this syntax isn't sufficient, you can use the . (dot) oper- ator to concatenate two or more strings. This operator is covered in a later section. 2.5.3.2 Single Quotes In addition to double quotes, single quotes may also delimit strings. However, in contrast to double quotes, single quotes do not support all the double quotes' escaping and variable substitution. The following table includes the only two escapings supported by single quotes: ' Single quote. \ Backslash, used when wanting to represent a backslash fol- lowed by a single quote--for example, \'.

Post Comment
Login to post comments