OOP - Implementing a Simple Class in PHP

Posted under » PHP » Methodology on 13 March 2009

Too illustrate the relationship between the class definition and its object, and to show the basic syntax used in PHP, in this example we

defines a simple class,

 Define a simple class that simply echoes the value given it.
class SimpleClass {
    public $data;
    public function echoMyData() {
        echo $this->data;

A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object.

instantiates an object based on that class,

 Create an object (sc_object) based on SimpleClass = instantiation
$sc_object = new SimpleClass();

and uses the object.

 Set a value for the data of the object = arrow sign
$sc_object->data = "Hello, world! ";

Now let us create another object and give it a different value.

$another_object = new SimpleClass();
$another_object->data = "Goodbye, world! ";

Use the class method to print out the value of our two objects.

 The arrow can also be used to call out a function from a class

// The output from this script will be:
//    Hello, world! Goodbye, world!

In words, the class SimpleClass is defined to have two members: a variable (properties, parameters) named $data and a function (method) named echoMyData(). The PHP statement new uses the class definition to create two objects, each of which references its own copies of the class members.

For more info. on PHP OOP.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data