Home arrow PHP arrow Page 2 - The PHP Scripting Language

Creating PHP scripts - PHP

This article describes the basics of the PHP scripting language, which is very easy to learn if you are familiar with any programming language. It is excerpted from chapter two of the book Web Database Applications with PHP and MySQL, written by Hugh E. Williams and David Lane (O'Reilly, 2004; ISBN: 0596005431).

TABLE OF CONTENTS:
  1. The PHP Scripting Language
  2. Creating PHP scripts
  3. Character encoding
  4. Expressions, Operators, and Variable Assignment
  5. switch Statement
  6. Changing Loop Behavior
  7. Automatic Type Conversion
  8. User-Defined Functions
  9. Static variables
  10. Managing include files
By: O'Reilly Media
Rating: starstarstarstarstar / 32
September 29, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

A PHP script can be written using plain text and can be created with any text editor, such as the Unix editors joe, vi, nedit, Emacs, or pico, or a Microsoft Windows   editor such as Notepad or WordPad. There are also several special-purpose PHP programming editors available, and a well-maintained list of these can be found at http://phpeditors.linuxbackup.co.uk/.

If you save a PHP script in a file with a .php extension under the directory configured as Apache’s document root, Apache executes the script when a request is made for the resource. Following the installation instructions given in Appendixes A through C, the document root on a Unix machine is:

/usr/local/apache/htdocs/

and in a Microsoft Windows environment:

C:\Program Files\EasyPHP1-7\www\

Consider what happens when the script shown in  Example 2-1 is saved in the file example.2-1.php in the document root directory and you view the file in a Web browser on the same machine.  Apache—when configured with the PHP module—executes the script when requests to the URL http://localhost/example.2-1.php  are made.

If you are working on a Unix host, and directory permissions don’t permit creation of files in the document root, it’s also possible to work in your user home directory. If the installation instructions in Appendixes A through C have been followed, a directory can be created beneath your Unix home directory and the permissions set so that the directory is readable by the web server. You can do this by running a terminal window and typing the following after the shell prompt (shown here as a%):

% mkdir ~/public_html
% chmod a+rx ~/public_html

The example file can then be created with the filename:

  ~/public_html/example.2-1.php

The file can then be retrieved with the URL http://localhost/~ user/example.2-1.php, where user is the user login name.

You can insert any of the code in this chapter into that file, or another one of your choice, and see what’s displayed by calling it up in a browser as we have shown.

Comments

Comments can be included in code using several styles used by high-level programming languages. This includes the following styles:

// This is a one-line comment
#  This is another one-line comment style
/* This is how you
  
can create a multi-line
  
comment */

Outputting data with echo and print

The print statement used in Example 2-1 and Example 2-2 is frequently used and can output any type of data. The echostatement can be used for the same purpose. Consider some examples:

print "Hello, world";
// echo works just the same
echo "Hello, world";
// numbers can be printed with echo too
echo 123;
// So can the contents of variables $outputString = "Hi!";
echo $outputString;

The difference betweenprintandechois thatechocan output more than one parameter, each separated by a comma. For example,echocan print a string and an integer together in the one message:

// prints "The answer is 42"
echo "The answer is ", 42;

Theprintandecho statements are also often seen with parentheses:

echo "hello";
// is the same as
echo ("hello");

Parentheses make no difference to the behavior ofprint. However, when they are used withecho, only one output parameter can be provided.

Theechoandprintstatements can be used for most tasks and can output any combination of static strings, numbers, arrays, and other variable types discussed later in this chapter. We discuss more complex output with printf( ) in the next chapter.

String Literals

One of the most common tasks in a PHP script is to output literal sequences of characters to create messages, headings, and other text that appear on HTML pages. A literal sequence of characters—a string literal or simply a string—can be included in a PHP script using quotation characters. PHP can create double- and single-quoted string literals:

print 'This works';
print "just like this.";

Because quotation marks are used to mark the start and end of strings, a quotation mark that is actually part of a string must be marked in some way. Marking a character so that it is treated as a normal character, instead of being part of the PHP syntax, is called escaping. Quotation marks can be escaped by putting a backslash before them:

print "This string has a \": a double quote!";
print 'This string has a \': a single quote!';

A simple alternative to including quotation marks in a string is to switch to the single-quotation style:

// And here are some strings that contain quotes
print "This string has a ': a single quote!";
print 'This string has a ": a double quote!';

To include a backslash character in a double-quoted string, use the escaped sequence\\. Tab, newline (line break), and carriage-return characters can be included in a double-quoted string using the escape sequences\t,\n, and \r, respectively. Inserting the white space characters\t, \n, and\ris often useful to make output more readable, however as HTML, white space is generally disregarded.

Unlike many other languages, PHP allows newline characters to be included directly in a string literal. The following example shows the variable$varassigned with a string that contains a newline character:

// This is Ok. $var contains a newline character
$var = 'The quick brown fox
       
jumps over the lazy dog';

This feature is used in later chapters to construct SQL statements that are easier to read in the PHP source code, for example:

$query = "SELECT max(order_id)
            FROM orders
           WHERE cust_id = $custID";

Variable substitution

Variable substitution provides a convenient way to embed data held in a variable directly into string literals. PHP examines, or parses, double-quoted strings and replaces variable names with the variable’s value. The following example shows how:

$number = 45;
$vehicle = "bus";
$message = "This $vehicle holds $number people";
// prints "This bus holds 45 people"
print $message;

PHP interprets the $ and the following non-space characters as the name of a variable to insert. To include the dollar signs in a double-quoted string you need to escape the variable substitution meaning with the backslash sequence\$.

When the name of the variable is ambiguous, braces{}can delimit the name as shown in the following example:

$memory = 256;
// No variable called $memoryMbytes
// Sets $message to "My computer has of RAM" $message = "My computer has $memoryMbytes of RAM";
// Works: braces are used delimit variable name
// Sets $message to "My computer has 256Mbytes of RAM"
$message = "My computer has {$memory}Mbytes of RAM";

When the string literal containing the characters$memoryMbytesis parsed, PHP tries to substitute the value of the nonexisting variable$memoryMbytes. Braces are also used for more complex variables, such as arrays and objects:

print "The array element is {$array["element"]}.";
print "Mars is {$planets['Mars']['dia']} times the diameter of the Earth";
print "There are {$order->count} green bottles ...";

We explain arrays in the next chapter and objects in Chapter 4.

We recommend using the braces syntax when including variables in string literals. It makes your code more readable, and saves you the trouble of remembering to escape characters.

Single-quoted strings aren’t parsed in the same way as double-quoted strings for variable substitution. For example, the characters$vehicleand$numberaren’t substituted in the following fragment of code:

$number = 45;
$vehicle = "bus";
// prints "This $vehicle holds $number people"
print 'This $vehicle holds $number people';



 
 
>>> More PHP Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: