We continue with the Part II of our coding technique,
the class, constructor, method and attributes.
ContructorIn object-oriented programming, a constructor in a class is a special type of subroutine called when an object is created dynamically through the keyword "new". Its purpose is to prepare the new object for use, often accepting parameters which are used by the constructor to set member variables which are required when the object is first created.
A constructor is similar to an instance method, but it differs from a method in that it never has an explicit return type, it is not inherited, and usually has different rules for scope modifiers. Constructors are often distinguished by having the same name as the declaring class.
ExamplesIn PHP (Version 5 and above) the constructor is a method named __construct(), which is automatically called by the keyword new after creating the object. However, constructor in PHP version 4 (and earlier) is a method in a class with the same name of the class. Because PortaMx supports PHP4, we use only PHP4 type constructor.
// the class definition
class Person
{
var $name; // a class attribute
// the constructor
function Person($name)
{
$this->name = $name;
}
// a method
function getName()
{
return $this->name;
}
}
Now we can create a new instance of the class by doing follow:
// define the classname
$class = 'Person';
// create the instance and call the contructor
$handle = new $class('Feline');
// now you can call the method getName() and echo the result
$result = $handle->getName();
echo $result; // write out "Feline"
If you use a method INSIDE a class or method, then you must call these with the keyword
$this.
Example:
// the class definition
class Person
{
var $name; // a class attribute
// the constructor
function Person($name)
{
$this->setName($name); // call the method setName
}
// method setName
function setName($name)
{
$this->name = $name;
}
// method getName
function getName()
{
return $this->name;
}
}
This have the same effect as the first example. The constructor is called on create a new instance and the constructor called the method setName($name). To test this. we create a new instance of the changed class:
// define the classname
$class = 'Person';
// create the instance and call the constructor
$handle = new $class('Feline');
// call the method getName() and echo the result
$result = $handle->getName();
echo $result; // write out "Feline"
Because we have now a method setName, we can change the name attribute:
// change the attribute $name
$handle->setName('PortaMx');
// call the method getName() and echo the result
$result = $handle->getName();
echo $result; // write out "PortaMx"
To be continued ...
Fel