Getting started with Haxe/PHP

A simple webpage with Haxe and PHP


You can also start developing websites very quickly with Haxe. Let's start with a simple HelloWorld example. Put the following code in the file Index.hx :
import php.Lib;

class Index {
    static function main() {
        trace("Hello World !");
    }
}

Now we need to compile this and create the PHP files from it. Create build.hxml so it contains the following content :

-php www
-main Index

You can now run the build.hxml by simply double-clicking on it on Windows, or, for other platforms, run the command haxe build.hxml in a terminal.

If everything goes well, it should create a directory www that contains the generated files. You can configure your webserver to point at the www folder to see the PHP code in action.

Web API

So far we've been only using the Haxe Generic API, available for all platforms. Now let's look at the ServerSide specific API, which is located in the package php. Modify your Index.hx file with the following content :

import php.Lib;
import php.Web;

class Index {
    static function main() {  
        var params = php.Web.getParams();
        var name = params.exists('name') ? params.get('name') : 'world';
        php.Lib.print('Hello ' + name + '!');
    }
}

This will use the php.Lib.print function that prints some raw string (without adding debug information). It will print the parameters sent by the browser.

Recompile it by double-clicking the build.hxml again, and visit http://localhost/?name=Haxe (assuming that your webserver is pointing at the generated folder www). It will display the request parameters for the URL that were sent by the browser.

There is also a lot of useful functionality available in the Web class.

Note that the php package tries to mimic as far as possible the neko one. This allows for easy switching between the two platforms

Converting php to haxe

A tool to convert existing php source code to haxe source code can be found here: http://phptohaxe.haqteam.com/

version #19388, modified 2013-05-29 10:47:33 by yar3333