Home arrow PHP arrow Page 2 - Classes as PHP Functions

Creating a Class - PHP

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.

TABLE OF CONTENTS:
  1. Classes as PHP Functions
  2. Creating a Class
  3. Adding an Attribute to the Objects
  4. Constructor Functions
By: Jacques Noah
Rating: starstarstarstarstar / 136
August 08, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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";
?>

As you can see, we can use attributes in a way that is similar to how we use variables.



 
 
>>> More PHP Articles          >>> More By Jacques Noah
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: