Object Oriented Programming in PHP5
Object Oriented Programming in PHP5 A WebApp Tutorial Adrian Giurca
Chair of Internet Technology, Institute for Informatics October 15, 2006…
Contents: Basic PHP Constructs for OOP, Advanced OOP Features, Public, Private, and Protected Members, Interfaces, Constants, Abstract Classes, Simulating class functions, Calling parent functions, Calling parent constructors, The special name parent, Serialization, Introspection Functions.
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("<table><tr><td>$this->body_text");
print(“</td></tr></table>");
}
}
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("<table><tr><td>$this->bodyText");
print(“</td></tr></table>");
}
}
// creating an instance
$box = new TextBox("custom text");
$box->display();
PHP class definitions can optionally inherit from a superclass definition by using the extends clause. The effect of inheritance is that the subclass has the following characteristics: • Automatically has all the property declarations of the superclass. • Automatically has all the same methods as the superclass, which (by default) will work the same way as those functions do in the superclass. In addition, the subclass can add on any desired properties or methods simply by including them in the class definition in the usual way…
Source: http://www.senc.es/
Download Object Oriented Programming in PHP5
Leave a Reply