How to Create Events / Handle Signals with PHP-GTK

How to Create Events / Handle Signals with PHP-GTK

When trying to create an event (or what’s called handle a signal), you may get the following error:

PHP Fatal error: Call to a member function remove() on a non-object in /home/user/Desktop/application.php on line 12

This error may come from the following code:

<?php
$window=new GtkWindow();
$button=new GtkButton("Click here");
$button->connect_simple('clicked','clicked_function');
$window->add($button);
$window->show_all();
$window->connect_simple('destroy',array('gtk','main_quit'));
Gtk::main();
function clicked_function() {
$window->remove($button);
}
?>

What’s wrong with the code, you may say? Well, let’s first understand what is happening.

  • $button->connect_simple('clicked','clicked_function') – we connect a signal callback to the clicked signal. The signal is emitted from the relevant GtkButton object when the end user clicks the relevant button. There is both a connect and connect_simple method for the GtkButton object. The difference between the two is connect returns the object it was called from (i.e. GtkButton for instance).
  • We make the signal callback to clicked_function function. We then try and remove the button from GtkWindow.

The problem? Scope. Because Gtk::main continues the application in a loop (which means it subsequently keeps looking out for events to occur – like this one), it means you can’t call an object from within a function (as it is technically not available), so we have to pass it through the optional parameters of connect_simple in order to use the GtkWindow remove method to remove the GtkButton object.

In theory, we actually have two options.

  • We make the two objects (GtkWindow and GtkButton) global in scope (remember we declare scope within the function or where ever it usually isn’t available).
  • As I said, we pass the objects as optional parameters.

Let’s show you both methods:

<?php
$window=new GtkWindow();
$button=new GtkButton("Click here");
$button->connect_simple('clicked','clicked_function');
$window->add($button);
$window->show_all();
$window->connect_simple('destroy',array('gtk','main_quit'));
Gtk::main();
function clicked_function() {
global $window;
global $button;
$window->remove($button); // now works
}
?>

<?php
$window=new GtkWindow();
$button=new GtkButton("Click here");
$button->connect_simple('clicked','clicked_function',$window,$button);
$window->add($button);
$window->show_all();
$window->connect_simple('destroy',array('gtk','main_quit'));
Gtk::main();
function clicked_function($window,$button) {
$window->remove($button);
}
?>

And there you have it. That’s how you handle events in PHP-GTK!

Similar articles : How to install PHP-GTK on Ubuntu 12.04?

Sharing