To react to a signal you must connect to it by specifying a callback
function for PHP-GTK to call when that signal is emitted.
Connecting a function to a signal is achieved by calling the
connect() method of the object.
The function that you register as the callback for a signal must have the
correct prototype. You can find what the prototype should be from the
reference section of this manual.
For example, if you wanted to connect to the
"clicked" signal of an instance of
GtkButton you should define a function that
accepts one parameter, which will be the button that was clicked.
The code below shows how you might create a window, add a button to it,
wait for it to be clicked and then, when it is clicked, open a new
GtkWindow containing a message.
Example 2.1. Signals and Callbacks
<?php
if( !extension_loaded('gtk')) {
dl( 'php_gtk.' . PHP_SHLIB_SUFFIX);
}
function shutdown()
{
print("Shutting down...\n");
gtk::main_quit();
}
function you_clicked($button)
{
$window = &new GtkWindow();
$label = &new GtkLabel("You clicked the button");
$window->add($label);
$window->connect("destroy","shutdown");
$window->show_all();
return false;
}
$window = &new GtkWindow();
$window->connect("destroy", "shutdown");
$window->set_border_width(10);
$button = &new GtkButton("Click Me!!");
$button->connect("clicked", "you_clicked");
$window->add($button);
$window->show_all();
gtk::main();
?>
|
The important part here is where we call
$button->connect();
The connect method here registers the you_clicked()
function as the callback that will be invoked when the
"clicked" signal is emitted by the
GtkButton widget. We also register the
shutdown() function as the handler for the
"destroy" signal for both windows so that we
can shut down the application properly.
With PHP-GTK you can register more than one function to be invoked when
a signal is emitted by a widget. This allows you to set up a whole set
of functions to be called in response to an expected action.
When more than one function is connected to a signal, the functions are
called in the order in which they were registered when that signal is
emitted.
Example 2.2. Signal Callback Order
<?php
if( !extension_loaded('gtk')) {
dl( 'php_gtk.' . PHP_SHLIB_SUFFIX);
}
function first($button)
{
print "First function has been called\n";
}
function second($button)
{
print "Second function has been called\n";
}
$window = &new GtkWindow();
$window->connect_object("destroy", array("gtk",
"main_quit"));
$button = &new GtkButton("Click Me!!");
$button->connect("clicked","first");
$button->connect("clicked","second");
$window->add($button);
$window->show_all();
gtk::main();
?>
|
In the above example we connect two functions to a button's
"clicked" signal. The first call to the
connect() method connects the
"clicked" signal to the
first()
function, the second call connects the
"clicked"
signal to the
second() function.
The output from this program would be:
First function has been called.
Second function has been called.
|