Friday, March 25, 2011

Creating A Class In PHP-Tutorial

Let's create a simple class to demonstrate the concepts discussed above. Create a new PHP document called sample_class.php. Our class is going to be called human.

We know that a human has legs and arms, which in our class are going to represent the attributes. And we also know that humans walk, eat and sleep. These will act as the methods.

Script: sample_class.php:


class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
echo "Jude has " .$jude->legs." legs";
?>

Here we have a new object created from our human class, called jude. We also have a simple result saying how many legs Jude has. Note how the variable "legs"(declared in the class) is used without the dollar sign in the echo statement.

As well as calling attributes, we can also modify the attributes in the same way. For example if we want the leg attribute to be increased by say, one, so that legs now equals three, then this is what we do:


class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
< style="color: red;" lang="EN-GB">$jude-
>legs++; //increase legs by one
echo "Jude has " .$jude->legs." legs";
?>

No comments:

Post a Comment

PHP | PHP Books | PHP Tutorials | PHP Development