Categories
PHP

Syntax Highlighting Using PHP

You can publish Syntax Highlighted PHP code easily using php’s built in functions:

  • highlight_string()
  • highlight_file()

 

<?php
highlight_string
(‘<?php phpinfo(); ?>’);
?>

The above code will generate the following HTML codes:

<code><font color=”#000000″>

<font color=”#0000BB”>&lt;?php phpinfo</font><font color=”#007700″>(); </font><font color=”#0000BB”>?&gt;</font>

</font>

</code>

 

As you can guess from the function name, highlight_file() takes a filename/path as a string parameter and returns the code.

 

Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf:

 

AddType application/x-httpd-php-source .phps

Categories
PHP

Lambda Function in php

Lambda function became very popular in Python. And from version 4.0.1, we have it on php as well.

Here’s a little snippet for your copy-paste comfort :

<?php
$newfunc 
create_function(‘$a,$b’‘return “ln($a) + ln($b) = ” . log($a * $b);’);
echo 
“Lambda Function: $newfunc\n”;
echo 
$newfunc(2M_E) . “\n”;?>

 

Give it a try on php-cli to check out J

Categories
PHP

php-gtk sample app

In my previous posts I wrote about php-gtk. Just a quick reminder: php-gtk lets you build desktop GUI applications for the GTK platform. These applications can be deployed on multiple platform without any hassle.

Here’s the source codes of a very simple “Hello, World!” application in php-gtk:

 

<?php

if (!class_exists(‘gtk’)) {

die(“Please load the php-gtk2 module in your php.inirn”);

}

 

$wnd = new GtkWindow();

$wnd->set_title(‘Hello world’);

$wnd->connect_simple(‘destroy’, array(‘gtk’, ‘main_quit’));

 

$lblHello = new GtkLabel(“Just wanted to sayrn’Hello world!'”);

$wnd->add($lblHello);

 

$wnd->show_all();

Gtk::main();

?>

 

If you go through the codes, you will get the structure very easily.

  • if (!class_exists(‘gtk’)) { die(“Please load the php-gtk2 module in your php.inirn”);}
    This line just checks if php-gtk is installed.
  • $wnd = new GtkWindow();
    Creates a new window.
  • $wnd->set_title(‘Hello world’);
    Sets the window title.
  • $wnd->connect_simple(‘destroy’, array(‘gtk’, ‘main_quit’));
    A bit complex. Connects the main_quit method of gtk with the “destroy” event of the window.
  • $lblHello = new GtkLabel(“Just wanted to sayrn’Hello world!'”);
    Creates a new label with the predefined text.
  • $wnd->add($lblHello);
    Adds the label to the main window.
  • $wnd->show_all();
    Shows all components.
  • Gtk::main();
    Starts the main loop. The application runs.

 

That was easy, wasn’t it?