Tuesday, April 25, 2006

PHP : Object Oriented Programming in PHP

Object oriented programming is the use of objects to represent functional parts of an application. With php too, you can do object oriented programming to reduce and simplify the code. Following code is an example of the use of a php class.

Code :

<?php
class web_developer{

        var $skills; # class variables
        var $sal;

        function web_developer($sal){
        $this->sal=$sal;
        }

        function getSal(){
        return $this->sal;
        }

        function addSkill($technology,$yrs){
        $this->skills[$technology]=$yrs;
        }

        function getSkills(){
        return $this->skills;
        }

} # class ends here

$x=new web_developer(2000); # creating a web_developer (an object) with associated salary !

echo $x->getSal()."<br />";# retrieving a property (sal) of the object

$x->addSkill('php',5); # adding his skill-set and no. of years of experience
$x->addSkill('perl',4);

$x_skills=$x->getSkills();# retrieving the property (skills) of the object

foreach ($x_skills as $k => $v){
echo "$k - $v<br />";
}
?>

Output in a browser:

2000
php - 5
perl - 4

No comments: