| PHP - Objects | | Print | |
PHP - Objects
An object is a compound data type that can contain any number of variables and functions. PHP's support for objects is somewhat limited in Version 4. PHP Version 5 will improve the object-oriented capabilities of PHP. In PHP 4, the object-oriented support is designed to make it easy to encapsulate data structures and functions in order to package them into reusable classes. Here's a simple example:
class test {
var $str = "Hello World";
function init($str) {
$this->str = $str;
}
}
$class = new test;
echo $class->str;
$class->init("Hello");
echo $class->str;
This code creates a test object using the new operator. Then it sets a variable called str within the object. In object-speak, a variable in an object is known as a property of that object. The test object also defines a function, known as a method, called init(). This method uses the special-purpose $this variable to change the value of the str property within that object.
Inheritance is supported by using the extends keyword in the class definition. We can extend the previous test class like this:
class more extends test {
function more( ) {
echo "Constructor called";
}
}
This means that the more class inherits from the test class and it also introduces the concept of a constructor. If a method inside a class has the same name as the class, it becomes the constructor function for that class. A constructor is called automatically when the class is instantiated.
Much more information is available at http://www.php.net/oop.
| Users' Comments (0) |
|
No comment posted





