Saturday, March 28, 2009

Class concepts and usage syntax in php

In php5 handling of objects is completely re-written and more features of object oriented concept is added. In this post I will write basic class definition and accessing variables, methods syntax.

Before proceed let's have an idea what is called class. A class is an abstract characteristics of a thing which includes thing's characteristics (properties) plus thing's behavior (operations).

In programming aspect a class contains a list of variables and functions. Variables represent attributes and functions represent what class objects can do.

Every class definition begins with the keyword class, followed by a class name, followed by a pair of curly braces. Within the braces class members and methods are defined. A pseudo-variable $this can be used within the class method which indicates the references to the calling object.

Note that $this variable is available if class method is called after creating a new instance. This can be also another object's instance. Without creating instance, if a method is called directly then $this variable will not be available.

Below is a simple example of usage class in php.

<html>
<body>
<?php
class MyClass1{
function display(){
if(isset ($this)){
echo '$this is defined = ';
echo get_class($this);
echo "<br />";
}else {
echo '$this is not defined.';
echo "<br />";
}

}
}

class MyClass2{
function display2(){
MyClass1::display();
}
}

$myclass1=new MyClass1();
$myclass1->display(); //$this will be available as function is called from an object context.
MyClass1::display(); //As we are not creating instance here so $this will not be available.

$myclass2=new MyClass2();
$myclass2->display2(); //$this will be available as function is called from an object context.
MyClass2::display2(); //As we are not creating instance here so $this will not be available.
?>
</body>
</html>


The output is,

$this is defined = MyClass1
$this is not defined.
$this is defined = MyClass2
$this is not defined.

Related Documents

No comments:

Post a Comment