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.
<? class human{ var $legs=2; var $arms=2; } //instantiate the class < style="color: navy;" lang="EN-GB">$jude = new human(); < style="color: navy;" lang="EN-GB">$jane = new human(); < style="color: red;" lang="EN-GB">$jude- >legs++; //increase legs by one echo "Jude has " .$jude->legs." Legs<br>"; echo "Jane has " .$jane->legs." legs"; ?>
...the result..
As you can see from the result, we can modify the instance of a class without touching the class definition itself. This re-usability is what makes classes so useful.
Now we can also add a new attribute to any of the objects (jane or jude). For example, let's add a new attribute to jane. The attribute is hair color:
<? class human{ var $legs=2; var $arms=2; } //instantiate the class $jude = new human(); $jane = new human(); < style="color: red;" lang="EN-GB">$jane->haircolor="brown"; $jude->legs++; //increase legs by one echo "Jude has " .$jude->legs." Legs<br>"; echo "Jane has ".$jane->haircolor." Hair and was created from the class <b>".get_class($jane)."</b> She also has <b>".$jane->legs." </b>legs"; ?>
So if we wanted to do the same thing for jude, we have to type all that out again, which is time consuming. Instead, we are going to automate this process by creating a function that will report on both jane and jude. So let's change the class to include this function:
<? class human{ var $legs=2; < style="color: red;" lang="EN-GB">function report(){ < style="color: red;" lang="EN-GB">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 variable $this enables us to refer to the object without knowing its name. Remember, when we created the class, we had no idea that an object called "jane" or "jude" was going to be created further along the line.
We said in our previous discussion that classes have attributes and methods, well, the function "report" is our method.
As you can see from the result above, the report() function has automated the process of reporting the attributes of an object. But we have a problem: not all humans have the same hair color, so we can't declare the hair color as an attribute of the class, and we can't create a hair color attribute each time we create a new "human" object, because it will make the code inefficient. So what can we do?