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
   

PHP ARTICLES

- 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...
- PHP: Building Concrete Validators
- Sanitizing Input with PHP
- Executing Shell Commands with PHP
- Handling File Data with PHP
- File Security and Resources with PHP
- ArrayObject PHP Class Examples
- ArrayObject PHP Class: An Introduction
- Getting File System Data with PHP
- PHP Tools for Working with the File and Oper...
- Working with the File and Operating System w...
- PHP Proxy Patterns: Completing a Blog


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 1 - Follow our Sitemap

Dev Shed Tutorial Topics: