June 17, 2009

PHP Advance

1. Basic PHP Constructs for OOP
The general form for defining a new class in PHP is as follows:
class MyClass extends MyParent {
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
//...
}
//...
}
As an example, consider the simple class definition in the listing below, which prints out a box of text in HTML:
class TextBoxSimple {
var $body_text = "my text";
function display() {
print("
$this->body_text");
print(“
");
}
}
In general, the way to refer to a property from an object is to follow a variable containing the object with -> and
then the name of the property. So if we had a variable $box containing an object instance of the class TextBox,
we could retrieve its body_text property with an expression like:
$text_of_box = $box->body_text;
Notice that the syntax for this access does not put a $ before the property name itself, only the $this variable.
After we have a class definition, the default way to make an instance of that class is by using the new operator.
$box = new TextBoxSimple;
$box->display();
The correct way to arrange for data to be appropriately initialized is by writing a constructor function-a special
function called __construct(), which will be called automatically whenever a new instance is created.
class TextBox {
var $bodyText = "my default text";
// Constructor function
function __construct($newText) {
$this->bodyText = $newText;
}
function display() {
print("
$this->bodyText");
print(“
");
}
}
// creating an instance
2
Object Oriented Programming in PHP5

January 22, 2009

Chamara Sandakelum Senarath


This Is My Blog.See My Profile.