I'm going to assume that you are already familiar with object oriented programming, if you're not, I suggest you get familiar with it before proceeding with this tutorial. You may also want to look in the PHP5 manual's section on object orientation so that all this makes more sense to you.
We'll begin with "porting" the simple Hello World! program to an object oriented nature, so that you can grasp the concept quickly. The first thing you have to do is to create a class. The most easy way to make your class is to extend one of the PHP-GTK 2 classes. Now, most applications have a GtkWindow as their top level widget. So does our Hello World program. So what we're going to do is to create a class that extends GtkWindow, so that it makes our job easier:
<?php class Hello extends GtkWindow { // code goes here. } ?> |
Now, our class extends GtkWindow, but that doesn't mean that GtkWindow's constructor is called automatically. This is the default behavior of PHP5 and hence we must call GtkWindow's constructor explicitly, using the parent keyword:
class Hello extends GtkWindow { function __construct() { parent::__construct(); } } |
function __construct() { parent::__construct(); $this->set_title('Hello World!'); $this->connect_simple('destroy', array('gtk', 'main_quit')); } |
Since this is a very simple program, we can finish all our tasks in the constructor itself. We simply put the code that we put in our procedural program into the constructor here. So we have the final program:
Example 8.1. Hello World - The Object Oriented Style
<?php class Hello extends GtkWindow { function __construct() { parent::__construct(); $this->set_title('Hello World'); $this->connect_simple('destroy', array('gtk', 'main_quit')); $label = new GtkLabel("Just wanted to say\r\n'Hello World!'"); $this->add($label); $this->show_all(); } } new Hello(); Gtk::main(); ?> |