A class is a function of PHP that has its roots in object oriented programming. The ability to use classes in PHP has been increasing with later versions. If you want to add the power of classes to your PHP programming, keep reading.
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 <b>".get_class($this)."</b> has <b>" .$this- >haircolor. "</b> hair,and <b>" .$this->legs. "</b> legs<br>" ; } } //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 <b>".get_class($this)."</b> has <b>" .$this- >hcolor. "</b> hair,and <b>" .$this->legs. "</b> legs<br>" ;} } //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.