I.Basic
Feature | PHP | JScript and Javascript | VBScript |
Example (print 1 to 10 on a web page) | <html> <body><?phpfor ($i=1; $i<=10; $i++) |
<html> <body><%for (i=1; i<=10; i++) |
<html> <body><%for i = 1 to 10 Response.Write(i & "<br>")next%> </body></html> |
Script Tags | <?php ?>
If short tags are enabled in PHP.ini:
If ASP tags are enabled in PHP.ini:
<%= return expression %>
|
<% %>
<%= return expression %>
|
<% %>
<%=return expression %>
|
End of statement | semicolon (;) is compulsory | End of line or optional semicolon | End of line |
Comments | // PHP comment 1 /* This is a multi-line Comment */ # PHP comment 3 |
// JScript comment
/* This is a multi-line Jscript Comment */ |
' VBScript comment |
Variables | Prefixed by $ | No prefix | No prefix |
Need to declare variables? | No, and every variable is preinitialised to type NULL, which is equivalent to false, the empty string and 0.
$AVAR = 123;
|
Optional. Error if variable not initialised when used.
var AVAR
|
Optional. Error if variable not initialised when used.
Dim AVAR
|
Loosely Typed Variables | Yes. This means that the type of a variable can be changed at run-time.
To change variable type, use typecasting or settype( )
|
Yes | Yes |
Case-Sensitivity | Yes for variables, no for function-names and reserved words | Yes for variables and reserved words | No |
Strings | Delimited by single-quotes, double-quotes or PERL heredoc style.
$avar = 'this is a string';$avar = "this is a string";$avar = <<<EOS this is a stringEOS; |
Delimited by single-quotes or double-quotes. | Delimited by double-quotes. |
String Concatenation | The . (dot) symbol.
$s = 'A' . 'B';
|
The + (plus) symbol.
s = 'A' + 'B'
|
The & (ampersand) symbol.
s = "A" & "B"
|
String Evaluation | Yes, variables embedded in strings are evaluated if string delimited by double-quotes.
$a = "A";
|
No | No |
Common string constants | Line feed: "\n"
Note that single-quoted 'n' is not converted to a line-feed for PHP. Only double-quoted strings are evaluated.
|
Line feed: "\n"
|
Line feed: vbLf
|
HTML encoding functions | htmlspecialchars($str) Converts < > & and " to their HTML entity equivalents, eg. < becomes <
urlencode( ) All punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding. Spaces converted to +.
urldecode( )All punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding. Spaces converted to +.
|
escape(str) All spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding
unescape(str) inverse of escape
|
Requires ASP Server object (and consequent COM overhead).
Server.HMTLEncode( ) Similar to PHP's htmlspecialchars.
Server.URLEncode( ) Similar to PHP's urlencode.
|
Regular Expressions | Built-in.
if (preg_match ("/php/i", $str))
|
Built-in.
if (str.match(/php/i))
|
Use COM object RegExp. Only available with the latest versions of VBScript (5.5 or later).
|
Dates | $adate = time();$adate=mktime(0,0,0,1,30,2000); |
adate = new Date();adate = new Date(2000,1,30) Dates are formated using the current locale configured in the control panel, so you have to hand-code date formatting or change your locale.
|
adate = Nowdate= CDate('2000-1-30') FormatDateTime(adate,2) Dates are formated using the current locale configured in the control panel, so you have to hand-code date formatting or change your locale.
|
Arrays | Declare with
For indexing use [ ]. Arrays begin with zero element.
Use sizeof(array) function to get size of array.
Arrays can be iterated over using:
$val = reset($arr);$max = sizeof($arr); |
Declare with
For indexing use [ ]. Arrays begin with zero element.
Use array.length to get size of array.
|
Declare with
For indexing use ( ). Arrays begin with zero element.
|
Associative Arrays | Yes
$avar = array();$avar['newton']='isaac';echo $avar['newton']; Note: You can append new elements to arrays with
|
Yes
avar = new Array();avar['newton'] = 'isaac';Response.Write(avar['newton']) |
Not built into the language, but can simulated using the Dictionary object (which is not thread-safe in VBScript 5.0). |
True and False | Has constants true and false.
The following also evaluate to false:
0 /* zero */"" /* empty string */"0" /* string with zero */ |
Has constants true and false.
Empty strings and zero will evaluate to false.
|
Has constants true and false.
Unlike PHP and JScript, zero does not evaluate to false.
|
Equality | == true if equal!= not equal Note that some functions can return 0 or false (false is typically used to indicate failure) depending on the context. For these functions, you will need to use === to determine whether 0 or false was returned. Some problematic functions: strpos, strrpos, strstr, stristr, strrchr
|
== true if equal!= not equal JScript does not have the 0/false problem.
|
= true if equal<> not equal |
Assignment statements | Allows C style shortcut assignments. For example, to append a string to a variable:
$avar .= 'append to end';
|
Allows C style shortcut assignments. For example, to append a string to a variable:
avar += 'append to end';
|
No shortcut assignments. |
Sending HTML to Browser | print $avar; echo "The avar variable '$avar' is a string"; |
Response.Write(avar); | Response.Write(avar); |
If statements | if (strlen($avar) == 0) { $avar = "abc";} else |
Similar to PHP and C. | if len(avar) = 0 then avar = "abc"else avar = avar & "end" |
While statements | while ($a > 0) {$a -= 1;} |
while (a > 0) a -= 1; |
while a > 0 a = a - 1wend |
For loops | for ($i=0,$m=9; $i<$m; $i++){ |
for (i=0,m=9; i<m; i++) { Response.Write(i);} |
for i=1 to 100 Response.Write(i)next |
Switch/Case | switch($aColor) {case 'red': do1;break;case 'green': do2;break; default: do3; break;} |
switch(aColor) { case 'red': do1 breakcase 'green': do2 breakdefault: do3; break;} |
select case aColorcase "red" do1case "green" do2case else do3end select |
II.Function&Classes
PHP | JScript and Javascript | VBScript | |
Function Example | function inc($val){ return $val + 1;} Procedures are functions that return no value.
|
function inc(val) { return val + 1;} Procedures are functions that return no value.
|
function inc(val) inc = val + 1end function |
Class Example | class parent { var property; function parent() { } function method() { }} |
class parent { property=value function parent() Inheritance not supported.
|
Not available |
Scope of Variables | Variables defined outside a function or class are available globally; variables defined in a class or function are available locally.
Unlike other languages, you must declare a global variable in a function or class before you use the variable, using the keyword global.
$globalvar = 1; |
Similar to PHP, except no need to declare global variables in functions. | Similar to PHP, except no need to declare global variables in subroutines nor functions. |
Call by Reference | Use & keyword in function parameters. | Simple types passed by value, complex types by reference in functions. | Use ByRef keyword in Sub or Function parameters. |
Default Parameters | Yes.
function A(param1="abc")
|
No | No |
Returning by Reference | By default, return is by value. For objects and arrays, we want to return by reference for superior performance. Use
function & getarray123() { $val = array(1,2,3); return $val;} Then in the calling code, use
$val = &getarray123(); |
Not an issue | Not an issue |
Classes | Inheritance and constructors supported. Parent constructor not called automatically during object creation, only derived constructor. No multiple-inheritance.
class child extends parent true
|
Classes and constructors supported. No inheritance. | Primitive form of classes in newer versions of VBScript. Constructors and destructors available. Inheritance not supported. See Using Classes in ASP |
Error Handling | Use @ to prevent a run-time error from halting execution.
$val = @function_can_fail(); The scope of @ is the current statement. The last error can be checked in $php_errormsg if track_errors=On is set in PHP.ini.
PHP5 supports try-catch exception handling.
|
Use try and catch.
try { function_can_fail()} catch(err) { |
Use On Error Resume Next to ignore run-time errors.
On Error Resume Next call sub_can_fail call sub_can_fail2 The scope of this statement is the current procedure. Use the global Err.number and Err.description to find out what was the last error number and description..
Newer versions of VBScript support try and catch.
|
III.PHP Equivalents for ASP Objects
Purpose | ASP Object | PHP Equivalent |
Writing HTML | Response.Write(str) |
print $str;echo $str;print_r $debug_str; |
Form, Cookie and QueryString variables. | Available in Request object. | These variables are available automatically as global variables if you have configured the following in PHP.ini:
variables_order="EGPCS" For security, I would recommend disabling register_globals (set it to OFF). Then the variables are only available in the arrays:
See examples below.
|
Redirecting to another location | Response.Redirect(url) |
Header("Location: $url"); |
Cookie Handling | Response.Cookies(cookiename) = newval avar = Request.Cookies(cookiename) |
setcookie($cookiename, $newval); $avar = $_COOKIE[$cookiename]; |
Application Variables | Application(appvarname) | Not available. Can be simulated with a database. |
Session Variables | Session(sessionname) = newval avar = Session(sessionname) |
In PHP4 or later, we mark certain variables as session variables using session_register($sessionname), and we call session_start( ) at the beginning of the .php page to restore the session variable values.
Note that we pass the name of the variable, and not the variable itself into session_register( ).
session_register('avar'); $avar = 99; session_start();/* 99 in $avar is overwritten now */print $avar; |
Form Variables | Request.Form("formvar")
Request.QueryString("getvar")
|
$_POST["formvar"];
$_GET["getvar"];
Alternately, GET and POST vars can be converted automatically to PHP variables. However this is a security risk if hackers are aware of the variable names used in your code.
|
Server Variables | There are many server variables. See ASP documentation. An example:
Request.ServerVariables("HTTP_HOST")
|
For ISAPI modules, the server varibles are stored in the $_SERVER array. For CGI, they are stored as environment variables, available from the $_ENV array or getenv( ). An example:
$_SERVER["HTTP_HOST"] using ISAPI module
$_ENV["HTTP_HOST"] using CGI module
See PHP, FastCGI and IIS for a more detailed discussion of high performance PHP on IIS.
|
Database Access | Microsoft's ADO technology is commonly used. | ADO can be simulated using the ADOdb database library. This PHP library emulates ADO, and is designed by the author of this article.
Limitations: only supports forward scrolling read-only cursors.
|
Buffering | Response.Buffer = trueResponse.Write("abc"); Response.Flush() |
ob_start();print "abc";ob_end_flush(); |
Script Timeout | Timeout is in seconds:
Server.ScriptTimeout(240)
|
Timeout is in seconds:
set_time_limit(240);
|