Making the jump to PHP

Introduction

Any modern day Web programmer has to master a whole range of languages and protocols, from client side scripting through to server side Apache modules. And now, here is PHP, one of the fastest growing server side scripting languages around and you need to add it to your current arsenal of Perl, Python, ASP, JSP, Javascript, Java…

In this article, I’ll point out some of the main areas where things are different from other languages (particularly Perl, Javascript and VB/ASP) to help you get started. After all, programming is programming whatever the language, and most of what you already know can be reused in PHP. Just watch out for those little details!

This article is not intended to be an in-depth look at PHP functionality. Rather, it is meant as a review of those PHP features that should be of particular interest to the Perl, Javascript, and VB/ASP programmer.

The following PHP features are introduced in this article and are summarized below:

  • Semicolons: Used to delimit statements.
  • Comments: Can represent any one of three different comment styles.
  • Variables: Loosely typed and preceded by a ‘$’ sign.
  • Variable Scope: Depends on the context under which it is being used.
  • Case Sensitivity: Variable names are case sensitive.
  • True and False Values: With True representing the integer value 1 and False representing an empty string.
  • Assignment, Equality, and Identity: Each a separate concept with its own operator.
  • Function call arguments: Are passed by value normally, use the ‘&’ operator to pass by reference.
  • String Manipulation: Comprehensive selection of operators and functions.
  • Assignment Shortcuts: Certain operators can be combined to form more concise code.
  • The Return Statement: Different types of values may be returned from a function.
  • Classes and Objects: PHP can create objects from classes.


Semicolons

White space is insignificant to PHP (except when defining a string). PHP scripts can be laid out with extra spaces, tabs and/or blank lines. This enables you to edit (and follow) your code more clearly, without having to worry about incurring a syntax error.

However, if you choose to insert a lot of white space, be sure to take care to delimit your statements! PHP statements end with a semicolon ‘;’. Forgetting this semicolon is a common syntax error. (Fortunately, however, the PHP compiler detects and reports these errors.)

In the following example, both statements are valid and produce the exact same output:

print( date("M d, Y H:i:s", time()) );

print(
    date("M d, Y H:i:s",
           time()
    )
)
;

⇒For VB programmers: In VB based languages, the end of the line delimits a statement. The next line is another statement (unless a continuation character is employed).

⇒For Javascript programmers: Unlike in Javascript, PHP requires that you use a semicolon.

Note: For further information, see:

http://www.zend.com/manual/language.basic-syntax.instruction-separation.php


Comments

PHP provides three different comment characters:

/* the multiline (or block) comment
   markers. These can cover multiple lines.
   But, they cannot be nested.
*/

// a single line comment
$myvar = 234; // A single line comment

# a different single line comment
$myvar = "Your name here:" # and another single line comment.

Both the // and # single line comment characters enable you to include comments from the comment character until the end of the line.

Note: Why two "single line comment characters"? Being an open source language, PHP is very accommodating. C++ programmers will relate to the // character, while shell scripting gurus will feel good about the pound sign.
⇒For VB programmers: I would recommend using the ‘//‘ style, as this is the most generally used comment character used in C++, Java and Javascript.

⇒For Perl programmers: You still have the ‘#’ character, but consider making use of the ‘//‘ character anyway, as this is the more widely recognized.

Note: Further information:
http://www.zend.com/manual/language.basic-syntax.comments.php


Variables

Unlike with most other languages (a notable exception being Perl), PHP uses a special character to define a word as a variable. Variables in PHP are prefixed by a dollar sign (‘$’).

Variables do not require formal declaration. They will automatically be declared when a value is assigned to it. In the example below, the variable myvar, is assigned a string value:


$myvar = "Some string";

Variables are "loosely typed". This means that their type does not have to be fixed. The examples below are both valid. PHP determines the variable type in either case:


$myvar = "1";

$myvar = 1;

PHP will assign a variable a different type as required. In the example below, PHP converts the variable to a string before passing it to the echo function:


$myvar = 123.4;

echo $myvar;

Similarly, in the following example, PHP:

⇒Converts the string 12 to an integer.

⇒Adds it to the integer 12.

⇒Passes it to the echo function, which will in turn, convert it to a string and "echo" it.

echo 12 + "12";

To ‘force’ a variable to be a particular type, you can use cast operators as shown below:

$myvar = (string) 12;

Alternatively, you can use PHP’s settype() function as follows:


$myvar = 12;

settype($myvar, "double");

⇒For Perl Programmers: Perl provides three different characters (‘$’, ‘@’, ‘%’) to differentiate the context of a variable, whereas in PHP there is only the one. This does not mean that all variables in PHP are scalar quantities! The ‘$’ sign merely indicates that the following word belongs to a variable. It says nothing about the type of the variable.

⇒For VB programmers: There is no need to define a variable before using it. For example, the following statement would not be required in PHP:


Dim x as Integer; ‘ VBScript

Note: Further information: http://www.zend.com/manual/language.variables.php.


Variable Scope

A PHP variable’s scope will depend on its context, meaning when:

⇒Defined within a function, a variable’s range is visible only within
that function.

⇒Defined within a class, variables can only be accessed through that class’
namespace (using the ‘->’ operator).

⇒Defined in the body of a script, however, a variable’s range is global as
it is visible throughout the script. Files that are include’d also enter
the global scope.

From within a function, use the ‘global’ keyword to refer to a variable from
the global namespace as shown in the following example:

function do_something() {
    global $user_name;  // declares the $user_name variable
                        // as defined outside of this function.
    // some code here
}

⇒For VB programmers: There is no equivalent to the Private or Public keywords used in VB. Effectively, everything is public.

⇒For Javascript programmers: In Javascript, the ‘var’ keyword is used to give a variable global scope. In PHP, however, the ‘var’ keyword is used to define a variable as belonging to a class, and the keyword is only valid within that class.

Note: Further information: http://www.zend.com/manual/language.variables.scope.php.


Case sensitivity

A frequent source of confusion is that while variable names are case sensitive, PHP keywords and function names are not case sensitive.


For example, the following two lines will have the same effect:

print("A message in a bottle.");
PRINT("A message in a bottle.");

However, the following two variables are different:

$myvar = 1;
$MyVar = 2;

Note: User created function names and class names are also case insensitive.

⇒For VB Programmers: Remember that variable names are case sensitive.


True and False values

Like any language, PHP needs to know whether something is true or false. For example, using PHP’s "equality" operator "=="(See next section) can be used to compare two values as follows: If ‘$x==$y’ then the statement is true, if they are not equal, the statement is false.

Similarly, a variable itself can be tested for whether its Boolean value is true or false. In PHP any value may be tested - numbers, strings, arrays and objects.

The following is a list of PHP rules for a Boolean evaluation:

⇒For numeric values: 0 is false, anything else is true

$x = 1;  // $x
if( $x ) // evaluates to true
$x = 0;  // $x defined as an integer type
if( $x ) // evaluates to false

⇒For string values: the empty string is false, all else is true

$x = "hello"; // $x is assigned a string
if( $x )      // evaluates to true
$x = "";      // empty string
if( $x )      // evaluates to false

Note: $x = "0" is the only exception: if($x) in this case evaluates to false

⇒For an array: an empty array is false, true if it has any elements

$x = array();  // $x is an empty array
if( $x )       // evaluates to false
$x = array( "a", "b", "c" );
if( $x )       // evaluates to true

⇒For an object: false if the object is empty (no defined methods or functions), true otherwise.

Class Yod {}   // empty class
$x = new Yod();
if( $x )       // evaluates to false
Class Yod {    // non empty class
    var $x = 1;
}
$x = new Yod();
if( $x )       // evaluates to true

PHP provides two built in constants, TRUE and FALSE. They are defined as:

⇒TRUE is the integer value 1

⇒FALSE is the empty string

They are not case sensitive. That is, ‘true’ and ‘True’, ‘false’ and ‘False’ will all work.

⇒For VB Programmers: PHP can be a bit confusing because variables are loosely typed and are sometimes converted before being compared. Just keep in mind that 0 and the empty string are false, everything else is true and that will work 99% of the time.

Note: Further information: http://www.zend.com/manual/language.constants.php


Assignment, Equality and Identity

PHP defines three separate operations: assignment, equality and identity. Each has its own operator, namely, ‘=’, ‘==’, and ‘===’ respectively, where:

⇒’=’ assigns a value to a variable,

⇒’==’ compares the values of two operands,

⇒’===’ compares their values and their types.

Some examples:

$var1 = 1;
$var2 = 1;
$var3 = "1";
($var1 == $var2)  // true, they are equal
($var1 == $var3)  // true, they are equal
($var1 === $var2) // true, they are identical
($var1 === $var3) // false, they are equal, but not identical.

Note: The ‘==’ and the ‘===’ operators do not function on arrays or objects. Using them in this manner will generate an error. PHP tests inequalities using the ‘!=’ operator.


Understanding PHP Assignments: They Do Not Mean "Equals"

Ten years of high school arithmetic, and you’re sure that "=" means equals, like 4 + 5 = 1. Not this time. In the following example, the assignment operator is used as part of an if statement condition:

$var4 = 4;
if($var1 = $var2)   // Evaluates to True, but for the wrong reasons
if($var1 = $var4)   // Also evaluates to True!!

Based on our high school conditioning, it would appear that the first if statement results in a True because of a valid equality, namely, $var1 equals 1 equals $var2.

But in fact, the order of operations has PHP assign $var2’s value of 1 to $var1. Since $var2’s value represents the positive integer 1, $var1 is now assigned this positive value, and the resulting condition is a positive integer. Positive integers expressed as a Boolean condition generate a True result (see previous section).

Now let’s look at the second if statement. Your grade 10 math teacher would swear to you that $var1 does NOT equal $var4 because 1 does not equal 4!!! So, the if statement equality should generate a false!

However, once more, let’s follow the PHP order of operations: $var1 is initially assigned the value of $var4, namely the integer 4. Since 4 is a positive integer, the if Boolean condition generates a True result.

⇒For VB Programmers: In VB, the ‘=’ sign serves two purposes, that of assignment and also of equality. For example:

' VBScript
aVar = 5
if( aVar = 5) ...

Note: The above code will NOT work correctly under PHP, as the ‘=’ sign will function as an assignment in both lines. In the ‘if’ test, assigning 5 to aVar will evaluate to True. The expression will always evaluate to True.

Note: Inequalities in PHP are tested with ‘!=’, not the ‘<>’ operator.

⇒For Perl Programmers: Note that the ‘==’ operator is used to compare any value type, not just numeric. There is no PHP equivalent of ‘eq’ and ‘ne’. For safe string comparisons use the strcmp() function.

⇒For Javascript Programmers: PHP acts very much like Javascript with regards to this issue.

Note: Further information: http://www.zend.com/manual/language.operators.assignment.php and http://www.zend.com/manual/language.operators.comparison.php


Call by value, call by reference

Most functions require arguments. For example, checkdate($m, $d, $y) has three arguments.

Normally, PHP will make a copy of each argument and pass it to the function as a parameter. When the function returns, these copies are
eliminated. This is known as ‘passing by value’, as only the value of the argument is given to the function. After the function call, the values of the variables remain unchanged.

Under most circumstances, this type of call is what we want, so PHP function arguments, by default, are passed ‘by value’. Sometimes, however, we want the function to act on the argument variable itself, and not on a copy.

In this case, we pass the arguments ‘by reference’, using the ‘&’ operator.

For example:

function double_it( &$x ) { // pass by reference
    $x = $x * 2;
}
$x = 2;
echo $x;  // prints '2'
double_it( $x );
echo $x; // prints '4'

Note: The ‘&’ operator can be used in the function definition, or when the function is called. The ‘&’ operator can also be used in assignment operations. For example, $myobj2 = &$myobj, where $myobj and $myobj2 now both point to the same variable.

Note: This usage of the ‘&’ operator is not the same as the ‘Bitwise AND’ operator.

⇒For VB programmers: The ‘&’ operator has the same effect as using the ByRef keyword.

⇒For Javascript programmers: Javascript has no similar operator. Simple types are passed by value, complex types are passed by reference.

⇒For Perl programmers: The ‘&’ operator is the same as the unary ‘’ operator.

Note: Further information: http://www.zend.com/manual/functions.arguments.php


String manipulation

Given that a major function of any web scripting language is string manipulation, one would expect a comprehensive selection of string operators for PHP as well.

For an excellent overview of PHP’s string operators and functions, refer to the article "Using Strings" by Nathan Wallace.

Note: PHP uses the ‘.’ dot operator to join strings

⇒For VB programmers: The ‘.’ operator is the same as VB’s ‘&’ operator.

⇒For Javascript programmers: The ‘.’ operator is the same as the ‘+’ operator.

⇒For Perl programmers: You should feel right at home here.


Combining operators

In addition to the standard set of operators, such as ‘+’, ‘-‘, ‘*’ and so on, PHP enables you to combine these operators with the assignment operator, such as ‘+=’ and ‘-=’. In this manner, PHP’s operators enable you to form more concise code.

The following operators can be combined with the assignment operator:

+ - * / % & | ^ . >> <<

The following example demonstrates this feature:

$myvar = 12;
$myvar += 14; // $myvar now equals 26
Note: The second line is equivalent to $myvar = $myvar + 14;
$myvar -= 12;  // $myvar now equals 14
$myvar *= 10;  // $myvar now equals 140
$myvar /= 7;   // $myvar now equals 20
$myvar %= 6;   // $myvar now equals 2
$myvar <<= 8="" 2;="" $myvar="" finally="" equals="" <="" pre="">

The combined operator is especially useful with the string concatenation operator:

$myvar = "My name is ";
$myvar .= " Asterix";

This is a great shortcut for creating long strings.

⇒For VB Programmers: There is really no equivalent in VB. These assignment shortcuts do not increase code efficiency, they are used merely as typing shortcuts.

Note: Further information: http://www.zend.com/manual/language.operators.assignment.php


Use of return statement.

Functions often need to return values to the calling program. In PHP, the ‘return’ statement is used to return a value.

For example:

function plus_one( $x ) {
    return $x + 1;
}
$y = 7;
$z = plus_one( $y); // $z = 8

We can use the return statement to return simple values, such as integers, or more complex ones, such as arrays (and objects). The return statement creates a copy of the item that is returned, so if it is a complex object, it may be better to pass the object by reference, rather than returning a copy. See the section above on the reference operator '&'. ⇒For VB Programmers: In VB, a value is returned by setting the name of the function to that value. To obtain the same result in PHP, you use the return statement. ⇒For Perl Programmers: In Perl, a function always returns a value - the value of the last expression evaluated. In PHP, if there is no return statement, nothing is returned from the function.

Classes and Objects
Although PHP does not try to be an Object Oriented Language, it does provide the 'class' keyword, which enables you to create objects. A full discussion of PHP classes and objects is beyond the scope of this article, so here are the highlights: ⇒Classes are described by the keyword 'class', and then a block containing the methods and attributes of the class. ⇒A class is instantiated into an object using the keyword 'new', e.g.:
$myObj = new JabberWock();

⇒All attributes and methods of a class are public.

⇒The class constructor has the same name as the class.

⇒Class methods and attributes are accessed with the pointer operator, ‘->’.

From the example above,

$myObj->writePoem(); // member function.

Further information can be found in the PHP manual and there is a good tutorial at http://www.zend.com/zend/tut/class-intro.php

⇒Other Languages: Classes and Objects are handled very differently in VB, Javascript and in Perl, although C and Java programmers will feel reasonably at home.


Summary

PHP as a language has its own way of doing things, and at the same time, has borrowed from other languages. In particular, most of the system level C functions from Unix have thin PHP wrappers around them, making the language immediately familiar to Unix C programmers. Throw in loose typing of variables, associative arrays and some unique constructs of its own, and you have the hottest script language on the Web.

In this article, I have covered the main differences between PHP and some other languages, particularly Web based languages such as Javascript and VB. You will find when you start programming with PHP, that most of what you have learned in other languages will translate very easily into PHP. After all, the basic principles are the same. Just keep in mind the differences I’ve listed above.

Lastly, PHP is quite happy to spit out error messages whenever you do something wrong, particularly with syntactic errors. These messages are usually descriptive enough to find the problem straight away. Online documentation for PHP is very helpful and will cover many of the above points in more detail than what was done in this article.