Friday, March 25, 2011

Constructors In PHP-Tutorials

This "problem" requires us to write special function called a "constructor function." A constructor function is a function that is written in a way that is very similar to a method of a class. The difference is that a constructor function will be called every time a new instance is made.

The syntax of a constructor function is:

function class_name(){
statements
}

Yes, the constructor function name must be the same as the class name. And within the function you can include all the attributes that are going to be included when an instance of the class is made. So, let's add a constructor function that will sort out our problem:


class human{
function human($hcolor){
$this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return "This ".get_class($this)." has " .$this-
>haircolor. "
hair,and " .$this->legs. " legs
" ;

}
}
//instantiate the class
$jude = new human();
$jane = new human();
$jane->haircolor="brown";
$jude->haircolor="black";
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>

The " $this->hcolor=$hcolor;" line will install the hcolor variable as an attribute when a new object is instantiated. So, instead of creating the hair color attribute every time we instantiate a new object, it is automatically called. The new class will look like this:


class human{
function human($hcolor){
$this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return "This ".get_class($this)." has " .$this-
>hcolor. "
hair,and " .$this->legs. " legs
" ;}

}
//instantiate the class
$jude = new human("black");
$jane = new human("brown");
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>

Conclusion

This article covered the basics of using functions and classes to make coding faster by cutting out code repetition. In the next part we will focus on inheritance, where one class inherits the attributes of another class.

No comments:

Post a Comment

PHP | PHP Books | PHP Tutorials | PHP Development