Welcome to the World of PHP

by Aaron Weiss

PHP has made server-side scripting into a whole new world. In this tutorial we explore the basic fundamentals of this tremendously popular open-source, server-parsed embedded scripting language.

By Aaron Weiss

In this overview we willl take a look at programming with PHP 3, the most popular version of PHP. Keep in mind, however, that PHP 4 was released in late-May of this year (PHP 4 Released, New "Zend" Engine).

Also key to keep in mind is that the art and science of computer programming is a much larger topic than any one language, and thus it cannot be the focus of this introduction. While PHP is accessible to programming newcomers, it will be easiest for those with even a small background in programming other languages such as BASIC, Pascal, C, JavaScript, and Perl.


Why PHP?

PHP's primary strength is in rapid development of dynamic Web pages. Developers without heavy programming experience can leverage PHP to complete tasks otherwise cryptic or obtuse in alternative languages, such as pulling records from a database and inserting them into an HTML table. The architecture of the PHP language is simple but powerful, and includes an extremely wide variety of functions suited for many tasks, both traditional data processing tasks and more Web-oriented functions.

On the other hand, some would argue that PHP remains an immature language, without the architectural elegance or extensibility of a language like Perl. Some developers find embedded scripting empowering, and program code is often mixed together with HTML structure; other developers find this approach disorganized and bug-prone, preferring separate development environments for each Web component. Developers with experience in Perl and especially mod_perl environments may find little reason to spend time with PHP, and this may be entirely justifiable.

That said, this tutorial is an introduction to PHP, and we assume you are at least a bit curious and anxious to get started!


The Very Basics

Unfortunately, installing and configuring your Web server to properly execute PHP pages is not really the focus of this article, and it can be a complex subject due to the variety of operating systems and Web servers that might be involved. From here on in, this article assumes that your Web server is already set up to serve PHP pages. If that's not the case, you'll want to begin at the PHP web site (http://www.php.net) to learn how to download and install PHP for your Web server. If you do not run a Web server, but rather use the services of a Web host, such as an Internet service provider, they will need to support PHP for you.

PHP is not a client-side language. That means that the browser never sees PHP -- only the Web server sees it, and executes it on-the-fly. The browser receives only a "normal" HTML page. To achieve this, PHP code is contained within a special tag, separating it from the other HTML on the page:

<H2>Today's Headline:</H2><BR> <P ALIGN="center">
<?php your php code here ?>

Consider a very simple sample, where the PHP code simply outputs the phrase "World Peace Declared":

what the web server seeswhat the web browser receives
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php print "World Peace Declared"; ?>
<H2>Today's Headline:</H2> <P ALIGN="center">
World Peace Declared

And of course, the Web browser will render on-screen:

Today's Headline:

World Peace Declared



PHP Structure

We have not yet discussed the PHP language itself, so let's focus on structure for now. The above page contains a small section of PHP code, which assigns a value to a variable $today. A second block of PHP code in the middle of the page outputs our headline, and a third block of PHP near the end of the page uses the $today variable to output the day of the week. Given that today (the day I'm writing this, not necessarily the day you're reading it!) is Wednesday, the above code would produce the page:

Today's Headline:

World Peace Declared

Today is Wednesday

Besides breaking up PHP code into multiple blocks, it is possible to include code from external files into pages. Sometimes you may wish to keep bits of code in its own file -- for example, HTML code that makes up a repeating element such as a logo or footer, or PHP code that makes up a function that will be used in several different pages. Returning to the previous example, suppose we break out the footer into its own file, and the initial PHP block into its own file:

setdate.php3: <?php 
footer.php3: <!-- begin footer -->
<SMALL>Today is <?php
print $today[weekday];

Now, we can use PHP's include() function to pull the above files into our example page:

<?php include ("setdate.php3"); ?> <H2>Today's Headline:</H2> <P ALIGN="center"> <?php print "World Peace Declared"; ?> </P><HR> <?php
include ("footer.php3");

The most common use for the include() function is, as seen above, to reuse certain components across several pages. Of course, your components will often contain much more code that the examples shown here! Also notice that each component is treated as an HTML page -- that is, it can contain HTML tags and any PHP code must appear within the <?php ... ?> tags.


Scalar Variables and Data

In most cases, PHP scripts will work with data -- to process, manipulate, and output. Data generally consists of nu mbers (numeric values) and letters or words (string values), although there are other types of data that PHP understands.

  • Integers and floating-point numbers are the two numeric data types in PHP.

    An integer is any whole number, such as 5, 10, 0, or -3.
    A floating-point number is any number with a decimal portion, such as 5.25 or -43.2339.

  • Strin g data is composed of any alphanumeric characters, such as words or symbols. Examples of strings include "pepsi", "Th e Simpsons", "23 skidoo", "Yahoo!", and so on.

Integer, floating-point, and string values are all known as scalar data because they are single data points. This is another way of saying that the number 5, or the word & quot;hockey", is just "one thing" (as opposed to, say, a list of things which we will see shortly).

In PHP, as with most programming languages, we use variables to contain a value -- a variable is like a label that refers to a value. The valu e assigned to a variable can change over time, as a result of processing and manipulation such as arithmetic. Variable names are usu ally words and are preceded with a dollar sign ($) in PHP. Let''s assign the value 100 to a variable named $price:

price = 100;

Code snippets such as the above are examples, but remember that PHP code in a page must always appear within & lt;?php ... ?> tags, even though we will not always write those tags around every single example snippet.

Also notice tha t good practice suggests we end PHP statements with a semicolon, as seen above. A statement is sort of like an English senten ce -- it is one full programming "thought". PHP statements are made up of expressions, where an expression is a mea ningful fragment of code. The previous example represents an assignment expression, because a value has been assigned to a va riable. In this case, the statement happens to be made up of only the one expression, which is perfectly fine. Many PHP statements a re made up of several expressions, which we''ll see later.

PHP determines the data type of a variable based on context, such as the context of the assignment expression:

$price = 100; $firstName = "Martin"; $breed = ''ferret''; $name = $f

In the first line above, which we have already seen, PHP assumes that 100 is an integer. In the second lin e, PHP understands Martin as a string because it is enclosed in double quotation marks. The same applies to ferret, al though enclosed in single quotation marks. In the fourth example, $name is assigned whatever value is currently held by $f irstName, which happens to be a string, so $name also contains a string value (Martin).

Note that in the fo urth example, $name receives a copy of the value in $firstName. Thus, if we then change the value of $name, thi s has no effect on the value held by $firstName.

Important: Variable names in PHP are case-sensitive. In other words, the variable $firstName is completely independent from a var iable named $firstname.

Why does a value''s data type matter to PHP, or to us for that matter? It matters when you need to perform an operation on one or more values. Operations include arithmetic, such as addition and subtraction. For example, you can add an integer and a floating-point value to yield another floating-point value:

$total = $price + 3.95; #
flat rate shipping

Above, $total will contain the value of whatever $price contained plus 3.95. Also notice t he use of a comment marked by a pound sign (#) -- PHP will ignore everything from the pound sign to the end of that line, so you can add annotations to clarify the purpose of a line of code.

But suppose you tried to add an integer and a string value?

$total = $price + "fruit juice";

Of course that doesn''t make any sense! PHP will try to resolve this problem by converting a string to a number, if the string looks like a number such as "4.50" (converts to 4.50) or even "10 a pples" (converts to 10). In the above example, PHP can''t make any number out of "fruit juice", so it will be given t he value 0, and 0 is what will be added to $price.

Variables are a crucial component of most programming languages in cluding PHP -- you will use them to store pieces of data, manipulate the data, and usually output some of the data.


Assigning a collection of values to an array variable is simple when using the array() construct:

lors = array("blue","indigo","yellow");

Or, if you know that you want to create an array $ colors but don''t yet know what values to fill it with, create an empty array:

$colors = array();

Adding new v alues to the array is a breeze:

$colors[] = "hunter green";

Now the array $colors contains four v alues. Oftentimes, you need to access a single item in an array, such as for output or a calculation. To do this, you need to refer to a key, which leads to the value you want. We haven''t created any keys ourselves in this example, and so PHP has created n umeric keys: The key for the first item ("blue") is zero, the key for the second item is 1, and so on, with the key for th e last item in a list being the number of items minus 1, since keys begin at zero. So, we can output the second color in the array v ia the key 1:

print $colors[1];

... will output "indigo". This type of indexed key system is great when you want to keep items in a specific order, but it is also limiting because the keys do not really mean anything. How do we k now we want the second key? In some applications we do know ... in others, this thinking just doesn''t work. The alternative is to c reate keys that are meaningful labels. For example, suppose our collection of colors was really a list of colors for our car. A car may have several colors, depending on the part of the car -- exterior, trim, fabric, dashboard. Here it makes sense to use keys whic h are labels more meaningful than a mere index:

$colors = array("exterior"=>"blue,"
"trim&q uot;=>"indigo,"
"dashboard"=>"hunter green");

Admittedly, this is one ugly car. Our list items have gained meaning but lost order -- which is fine, since this list is n ot about order. It''s now easy to output the fabric color of this car, because "fabric" is a key in the list:

nt $colors[fabric];

... will output "yellow."

Once an array has been built, typically it must somehow be manipulated, so as to sort it or simply output each of its values. PHP contains a variety of functions for working with an array. Mo st of these will not be covered here. Let''s say, though, that we wanted to output each of the items in $colors, along with t he key associated with that item. The general procedure for "stepping through" an array and processing each of its items w ill apply to many arrays you use in the future -- let''s use this procedure on $colors.

while (list($key,$value) = e
ach($colors)) {
print "$key: $value<BR>";

Although we have not yet discussed the while loop yet, bear with us! The above code sets up a loop, or a series of repeating steps. The each() function returns a list (array) of values corresponding to the key and value for a single item in the array. These returned values are assigned on-the-fly to $k ey and $value, courtesy of the list() function. The print statement simply outputs the key and value for th e current item in the list -- of course, you could do much more complex things with these values at this point in the code. Each tim e the loop returns to the while statement, it gets the next item in the array. When the array is completed the while l oop will end.

In the browser, the above code would output:

exterior: blue trim: indigo fabric: yellow dashboard: hun
ter green

Notice the order of our output, though -- same order that these items were defined earlier in our original arr ay() statement. Suppose instead that we''d like to sort this array alphabetically by key, so that "dashboard" appears first and "trim" last. Simply, use PHP''s ksort() function to sort $colors by key, and then step through the array as before:

ksort ($colors); while (list($key,$value) = each($colors)) {
print "$key: $value<BR>" ;

The PHP reference manual details a variety of ad ditional functions for managing your data arrays and performing nifty acrobatics.


PHP Variables and Web Forms

Note that addToMaillist is a fictional function, that we might have created to place the user's e-mail address into a text file somewhere.

Because PHP migrates form field names into variables, you may wish to construct form field names with an eye toward their resulting data structure in PHP. For example, suppose you have one form that asks for information about a recipient of some sort. You may want to contain that form's values inside a $recipient array, for example, to improve data management inside your PHP script:

<FORM action="process.php3" method="get"> Please enter the recipient's e-mail address: <INPUT type="text" size=20 name="recipient[email]"><BR>
Please enter the recipient's full name: <INPUT type="text" size=20 name="recipient[name]"><BR>
<BR><INPUT type="submit"> </FORM>


<?php while (list($key,$value) = each($recipient)) { print "$key: $value<BR>"; } ?>

The HTML form above was migrated into a PHP array named $recipient with the keys email and name. Above, our PHP code simply reproduces the loop we saw earlier and outputs each key and value in this array, for example (depending on what was submitted in the form):

email: cat@doglover.net name: Mrs. Kitty


Operations and Co mparisons


This statement actually consists of three expressions: the assignment operation, between $val3 and everything to the right of the equal sign; the addition operation between $val2 and the expression to the left of the plus sign; and finally, the subtraction operation within parentheses. Why the parentheses? It raises the issue of operator precedence. When an expression contains several operators, PHP has to determine in what order to perform the operat ions. Sometimes this matters greatly. Consider:

$val1 = 2 * 4 - 3;

What value should be assigned to $val1? If w e first multiply 2 and 4, and then subtract 3, the result would be 5. But if we first subtract 3 from 4, and then multiply that by 2 , the result would be 2. PHP has a set of precedence rules which define which operations take precedence -- in this case, multiplica tion is of higher precedence than subtraction, so in this case PHP would come up with the first interpretation, resulting in a value of 5.

To be honest, the operator precedence rules can be quite difficult to remember. Rather than memorizing them all, often a better approach is to use parentheses to group operations -- this way, we can determine our own precedence. For example, we can u se parentheses to determine either of the previous two interpretations:

$val1 = (2 * 4) - 3;
$val1 = 2 * (4 - 3)

The first example will yield 5, while the second will yield 2. It''s usually better to use parenthetical grouping this wa y rather than relying on PHP''s implicit precedence rules because 1) they can be difficult to remember, and 2) the above code will b e easier to understand by a human at a later time.


String operators work with characters rather t han numbers. And of course you can''t really add, subtract, or multiply the words "hot" and "tamale." Then again , maybe you can "add" them, if by that you mean string them together. In fact, this is called concatenation, and it is the only string operator available in PHP. Rather than a plus sign, the PHP concatenation operator is a single dot, or period. I magine that $firstName contains "Woodrow".

$fullName = $firstName . "Wilson";

Now, $ fullName will contains "WoodrowWilson". Whoops -- we''d probably want a space between those words, something to keep i n mind when you concatenate strings:

$fullName = $firstName . " Wilson";

Simple, indeed.


PHP''s basic assignment operator is already familiar, being a simple equal sign (=). You can also combine the e qual sign with an arithmetic or string operator to make a "shortcut" assignment. Confused? Let''s illustrate -- suppose th at you''d like to add a value of 5 to whatever value is currently contained in $val1:

$val1 += 5;

Thus, if $val1 was previously valued at 10, after the above statement it would contain 15. Similarly, you can use the same shortcut fo r string concatentation, if you want to add a string to the end of an existing string. Suppose $name contains "Thelonius ":

$name .= " Monk";

And now $name will be "Thelonius Monk".


Comparing two values is frequently useful -- is a purchase total below a certain threshold, or is does one word come bef ore another alphabetically? PHP''s team of comparison operators is here to help! A comparison operator ultimately retu rns either a true or a false value, depending on the result of the comparison. What you do with this result value can vary, and we''ll see this more closely when we talk about control statements. For the examples below, let''s assume the following va riable values:

$val1 = 15; $val2 = 7; $name1 = "Martin"; $name2 = "Michael&qu

PHP Comparison Operators

OperatorDescriptionExamplesYield s
EqualityTests whether two expression s are of equal value. For strings, the two must be exactly the same.
$val1 == $val2
$name1 ==
InequalityTests whether two expressions are not equal, or for strings, not exactly the same.
$val1 != $val2
$name1 != $name2
Less thanTests whether the left-hand expression ha s a value smaller than the right-hand expression. For strings, smaller means "comes before alphabetically."
$val1 < $val2
$name1 < $name2
Greater thanTests whether the left-hand expressi on has a value greater than the right-hand expression. For strings, greater means "comes after alphabetically."
$val1 > $val2
$name1 > $name2
Less than or equal toTests whether the left-hand expression is of equal or lesser value than the right-hand expression.
$val1 <= 15
$name1 <= "Martin"
Greater than or equal toTests whether the left-hand expression is of equal or g reater value than the right-hand expression.
$val2 >=6
$name2 >= "Manfred" 


Let''s raise the stakes: comparing t wo values is one thing, but sometimes you need something more, such as the ability to compare several comparisons! Let''s be logi cal about this, and use PHP''s logical operators. Suppose for example that you need to know whether $val1 i s of lesser value than $val2, and also whether $name1 is of greater value than $name2.

Remember t hat each comparison expression yields a true or false value. For the record, PHP does not actually possess true or false values, kno wn as Boolean data types. Rather, PHP considers the numeric value zero (0), or the string values "0" or empty "" to be false. Any other value, such as 1, or 3, or "cat", is considered to be true. A logical operator compares these true or false values. For example, using PHP''s and logical operator:

($val1 < $val2) and ($name1 > $name2)

Because this code fragment is not a full statement, there is no closing semicolon. Rather, we see parentheses grouping two expres sions. The left-hand expression will evaluate to the value false, if we assume the example values used in the comparison operator table. The right-hand expression will also be false, since "Martin" does not come after &quo t;Michael" alphabetically. The and operator will therefore compare the values "false and false". Because this operator returns true only when both expressions are true, the above expression will ultimately return false. That can be hard to fo llow, so let''s look at a summary table.

PHP Logical Operators

NameDescriptionExampl eYield
AndTrue if both left-hand and right-hand expressions are true.
(5>2) and (3>2) (2>5) and (3
true false
OrTrue if either left-hand or right-hand expression is true.
(5>2) or (2>7)
("h">"a") or (1<3)
true true
Exclusive OrTrue if either left-hand or right-hand expression is true < i>unless both are true.
("ar">"ac") xor (9>2) (3==3) xor ("f"==&q
true false
N otNegates the expression it precedes, true if the expression is not true.

Understanding all of these ope rators can certainly be exhausting!

Just as eye fatigue sets in -- a jolt! We''re about to string together everything we''ve learned so far, with the magic of control statements. Things will get much more exciting from here on in.



the "if ... else" statement

A programming classic -- the if ... else statement is u sed to execute a block of code when a given condition is true. Optionally, you can execute an alternative block of code if the condi tion is false, or test additional conditions.

if (conditional expression) { ...code to execute if true...
el se {
...code to execute if false...

For instance, you might print out a special welcome only if the user su bmitted the name "Harry":

if ($name == "Harry) {
print "Hello Harry, my name is also Harry!";< br>}

Perhaps you set a shipping rate of $5 for total orders below or equal to $25, and $10 for total orders above $25:

if ($total <= 25) {
$total += 5;
else {
$total += 10;

An optional clause, elseif, lets you test alternative conditions before dropping out to the else clause. For example, suppose the shipping rate is $5 for orde rs of $25 and below, $10 for orders above $25 up to $50, and $15 for orders above $50.

if ($total <= 25) {
$total += 5;
elseif ($total <= 50) {
$total += 10;
else {
$total += 15;

Notice that the elseif clause will only be evaluated if the first condition ($total <= 25) should fail, so we know that $total is at least 26 b y the time we evaluate whether it is less than or equal to 50.

the "while" statement

Another classic programming technique is the loop, where one or more statements are executed repeatedly either while or un til a certain condition is met. A while loop is probably the simplest loop statement, in PHP or any other language for that m atter. Let''s count to 100:

$counter = 0;
while ($counter <= 100) {
print "$counter<BR>";
$co unter++;

On each pass, or iteration as they say, through the while loop the condition is tested. As long as the condition remains true, the statements inside the while loop (inside the curly braces which define the "statement block ") are executed. Notice that this script will output the numbers 0 to 100, because $counter is not incremented to 1 unti l the end of the first pass. Also note that if the condition were false initially, the statements inside the while loop would never be executed -- which may be fine, depending on the scenario. The important thing about a loop such as while is that th e condition must eventually prove false, otherwise the loop will never end and very bad things may happen -- the computer cou ld lock up, become unresponsive, or the programming language may produce an error. Because we increment $counter on each pass , it will eventually surpass 100, causing the condition to become false.


the "do...while" stat ement

Very similar to while, this variation simply moves the conditional check to the end of the statement blo ck:

 $counter = 0;
do {
print "$counter<BR>";
while ($counter <= 100);

In this case the output would be exactly the same as the output from our while example -- the numbers 0 to 100. The di fference is that if the condition proved false on the first pass, the statement block would have been executed at least once, as opp osed to never in the case of the while statement.


the "for" statement

In many respects the for loop is similar to while, except that all parameters are set forth at the outset. These for statements are often used to repeat a sequence a given number of times. Repeating our example, suppose we want to output a count from 0 to 100:

for ($counter = 0; $counter <= 100; $counter++) {
print "$counter<BR>";

One typically sets up three parameters in the for statement, as seen above: The first sets an initial value for the conditio nal variable; the second specifies the condition to test; the third modifies the conditional variable on each iteration, or pass thr ough the loop.

gate hopping with "break" and "continue"

You can further modify prog ram flow within a conditional loop using PHP''s break and continue statements. The break statement will immedia tely exit the loop, regardless of conditions, while continue will skip ahead to the top of the loop and the condition test, i gnoring any remaining statements in the statement block for the given pass. Let''s return to our for statement example, but s uppose we want to output only those numbers divisible by two.

for ($counter = 0; ; $counter++) { if (($counter % 2) != 0) {

print "$counter<BR>";
if ($counter >= 100) {
} }

Several poi nts are illustrated above. First, we can eliminate the condition from the for statement. This will cause the loop to repeat i ndefinitely unless there is a break statement somewhere to quit the loop, which is exactly what we''ve done. We''ve tested th e condition within the statement block, and if the counter surpasses our limit, the break statement is executed. Also notice the first if statement in the statement block: the conditional test compares the value of $counter modulus 2 (the rema inder of this division) to zero. If the modulus is not zero, then we know that the counter value was not divisible by two and we iss ue the continue statement. This will skip the rest of the statements and return to the for, resulting in no output for that pass.



The Function of Functions

So, $val2 will contain 5.

It is not possible to cover all of PHP's built-in functions as there are so many. But it's also not necessary, since you understand how to work with a function, you need only consult the PHP function reference to browse available functions and their usage details -- what values they accept and what values they return.

We're more concerned here with coding your own functions, which is not an uncommon thing to do. Let's say you would like to code an "is a jerk" function -- it accepts someone's name and simply returns their name in the sentence "so-and-so is a jerk." (This is a very mature example to be sure.)

function is_a_jerk ($name) {
return "$name is a jerk!";

A function by itself does not do anything until it is called. We call our new function from within a statement:

print is_a_jerk("Little Johnny Long Pants");

The function does not itself print the result, it simply returns the result; in the above case, this result is then handed to the print function which triggers the output:

Little Johnny Long Pants is a jerk!

And it's true, he is. Let's consider a more full-figured example of a homegrown function. Imagine that your function accepts a purchase subtotal and a "ship to" state, and must return a final total incorporating the subtotal, applicable shipping, and applicable tax if the state is one where your store has a physical presence (New York, New Jersey, and West Virginia in this example).

function calcFinal ($subTotal,$shiptoState) {
#First calculate shipping surcharge
if ($subTotal <= 25) {
$subTotal += 5;
else {
$subTotal += 10;

#Setup array of taxable states with tax rates
$taxStates = array ("NY"=>0.075,"NJ"=>0.04,"WV"=>0.035);

#Add state tax
$subTotal *= 1+$taxStates[$shiptoState];

#Done, return results
return $subTotal;

Our new function calcFinal accepts two parameters, the first being the subtotal and the second being the state (actually, the two letter state abbreviation is what we'll use). Using a variation on our previous if statement, the subtotal is boosted with the shipping surcharge. Next, we create an array where each item key is the two-letter abbreviation for a taxable state and each value is the tax rate multiplier (7.5% for NY, for example).

To add sales tax to our subtotal, we add 1 to the tax multiplier and multiply $subTotal by this value, reassigning the result back to $subTotal. Why? If the state were NJ, the subtotal would be multiplied by 1.04. If the state were FL, the array would return a value of zero since there is no key "FL". We add 1 to this value, therefore multiplying $subTotal by 1, in essence adding no tax.

Finally, the subtotal is returned to the calling expression. The "calling expression" can be any valid expression -- imagine that we use an if statement to determine if the total cost exceeds a given threshold and, if so, offering a discount on a future purchase. Suppose that $purchase holds the current value of items purchased:

if (calcFinal($purchase) >= 1000) {
print "Congratulations, you have earned 15% off your next purchase!";

Functions are a very important way to segregate and enclose specific tasks, especially tasks which may be called upon repeatedly from different statements in a page.



Object Orientation

What might be an object? We could say that the concept of a "car" is an object. A car can possess a number of variables -- a list of colors, model name, model year, manufacturer, wheel size, fuel capacity, invoice price, and so on. We could even imagine that this "car" object has some functions -- a function that determines dealer price based on invoice price and certain features, for example; or a function that determines fuel efficiency based on the variables of engine type and vehicle weight. The point is, all of this "stuff" is part of the "car" object.

In PHP, as in other object-oriented programming languages, you begin by creating a class, which is like a blueprint of an object. Rather than create a specific car object, for example, we create the outline of what a car object is and can contain.

class Car {
var $colors;
var $modelYear;
var $modelName;
var $modelMake;
var $invoice;
var $options; function dealerPrice ($carObject) {
#add the values of each option to the invoice price
while ( list($option,$cost)=each ($carObject->options) ) {
$subTotal += $cost;
return $carObject->invoice + $subTotal; }

Voila -- we've just created the blueprint, or class, for a car object. The object has four scalar variables and two arrays ($colors and $options), as well as one function. The function simply sums up any values in the $options array and adds the result to the invoice price, resulting in what we're calling the "dealer price" (a pure fiction!).

Blueprint in hand, we can build an actual car object, or what is known as an instance. Suppose we want to create an instance of a new Porsche Boxter:

$boxter = new Car;

We've instantiated the car class, and now own a new but empty $boxter object. To access variables within the object, use the -> constructor:

$boxter->modelMake="Porsche"; $boxter->invoice="85000";
$boxter->colors=array ("exterior"=>"red","interior"=>"black");
$boxter->options=array ("turbo"=>5000,"anti-theft"=>2500);

Assuming all values were in place, we could access the boxter object's function to calculate dealer cost:

if ($boxter->dealerPrice($boxter) > 90000) {
print "Sorry, you can't afford a
$boxter->modelYear $boxter->modelMake $boxter->modelName";



The PHP Web site, http://www.php.net, is the primary source of information and documentation for this language although a few published books have begun to hit the virtual shelves. Spend some time with PHP and see if it's right for you. No single tool is ideal for all projects, and it's always nice to have a bulging tool belt -- which is precisely what makes PHP yet another open source success.

Back to Introduction ->

This article was originally published on Friday Jul 7th 2000
Mobile Site | Full Site