Posts Tagged ‘hybrid code’

Dr. JavaScript and Mr. PHP

Wednesday, January 21st, 2009

In my last post I wrote about JavaScript variables.  It stemmed from realizing that the dollar sign ($) was a valid character in JavaScript.  I struggled to find any use for all of these new characters – other than making code unreadable.  One thing stuck out in my mind.  An old episode of Hak .5 where Billy Hoffman described a worm that would be written in a hybrid of Perl and JavaScript.  A Dr. Jekyll and Mr. Hyde scenario where the worm would embed itself in a web page and search for a “host”, and then infect that host.  That host would then serve pages with the worm embedded in it, creating exponential growth.  Unfortunately at the time he didn’t have a proof of concept.

Hybrid Means Better Gas Mileage

Unlike Billy’s technique I chose to use PHP instead of Perl.  Many of the language constructs are identical between PHP and JavaScript.  However there are few snags.

  • PHP scripts have to start and end with ‘<?’ and ‘?>’ respectively.
  • PHP variables must start with a ‘$’.
  • Most of JavaScript’s standard functions are wrapped in objects.  Math, String, etc.
  • PHP uses the ‘.’ for concatenation, while JavaScript uses ‘+’.
  • PHP uses C++ style definition for objects, while JavaScript uses a prototype definition.
  • JavaScript uses the C++ style const keyword to define constants, while PHP uses the define() function.

The Lucky Ones

Not all of these problems can be worked around, but enough of them can be worked around that functioning code can be written.

PHP scripts have to start and end with ‘<?’ and ‘?>’ respectively.
The workaround for this is to run the script using the eval() function.  The PHP’s eval() function doesn’t require the opening and closing tags as feature.
PHP variables must start with a ‘$’.
The dollar sign is a valid character in JavaScript variables, so starting them with the dollar sign poses no problem.
Most of JavaScript’s standard functions are wrapped in objects.  Math, String, etc.
PHP.js can be used to wrap the standard JavaScript functions.  Acting as a compatibility layer.
JavaScript uses the C++ style const keyword to define constants, while PHP uses the define() function.
PHP version 5.3.0 allows for the const keyword.

Taking the Plunge

As a proof of concept I wrote a small function to calculate  the great circle distance.  It computes the distance in both PHP and JavaScript.  You can find it here and hybrid PHP / JavaScript code here.