Thursday, 2 August 2012

A Simple PHP class

Let’s start our thinking of the class with a simple PHP class example. In this example we want to print a variable value.

<?php
class SimpleClass
{
    // property declaration
    public $variable = 'This is state of an PHP object';

    // method declaration
    public function display_variable() {
        echo $this->variable." Under PHP class Method";
    }
}
?>

Save the code and run it. This program print nothing. It is important to remember that a class declaration only creates a template, it does not create the actual object. To print the variable value you need to create a instance of this class.

Creating an instance

You can create an instance using new operator. A class must be created before instantiating object. So the whole code is

<?php
class SimpleClass
{
    // property declaration
    public $variable = "This is state of an PHP object";

    // method declaration
    public function display_variable() {
        echo $this->variable." Under PHP class Method";
    }
}
$instance=new SimpleClass();
$instance->display_variable();

?>

Run this code and it will show This is state of an PHP object Under PHP class Method. In the display_variable method we use this keyword. It says that it is the variable of this class not other class. 

No comments:

Post a Comment