Subscribed unsubscribe Subscribe Subscribe

Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

Preprocessing PHP Code with GCC

CCPP is a C compatible preprocessor for PHP. It might be useful when you migrate old PHP4 codes to PHP5 with keepking compatibility between the versions. However, I bumped into an idea that I could just use GCC for it.

Let's test the idea.

Original Code

PHP has had exceptions since PHP5. You have to handle errors by some different way in PHP4. You can handle the difference using preprocessor directives:

#include "php_version.h"

<?php
function inverse($x) {
    if (!$x) {
        $message = 'Division by zero.';
#if PHP_VERSION >= 5
        throw new Exception($message);
#else
        trigger_error($message);
#endif
    }
    return 1/$x;
}

#if PHP_VERSION < 5
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo $errstr;
}

set_error_handler('myErrorHandler');
#endif

#if PHP_VERSION >= 5
try {
#endif
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
#if PHP_VERSION >= 5
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
#endif

echo "Hello World\n";
?>

Run gcc with some command line options like below:

$ gcc -E -P -x c original.php | cat -s > preprocessed.php

cat -s removes redundant linefeeds generated by gcc.

PHP_VERSION == 4

<?php
function inverse($x) {
    if (!$x) {
        $message = 'Division by zero.';

        trigger_error($message);

    }
    return 1/$x;
}

function myErrorHandler($errno, $errstr, $errfile, $errline) {
    echo $errstr;
}

set_error_handler('myErrorHandler');

    echo inverse(5) . "\n";
    echo inverse(0) . "\n";

echo "Hello World\n";
?>

I didn't actually run the code above (I don't have installed PHP4 interpreter), so I can't assure that the code works or not ;)

PHP_VERSION == 5

<?php
function inverse($x) {
    if (!$x) {
        $message = 'Division by zero.';

        throw new Exception($message);

    }
    return 1/$x;
}
try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo "Hello World\n";
?>