ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


PHP Foundations Introduction to PHP Objects, Part 1

by John Coggeshall
07/18/2002

Introduction

Welcome back! Last time we met, I discussed with you the concept of using multiple files to store your PHP scripts.

In today's column, I'll be introducing one of the more interesting and useful methods of writing PHP scripts -- the object-oriented method. Those of you who might have experience with an object-oriented programming language such as Java or even C++ will find themselves right at home with most of the concepts I'll begin outlining here. However, be warned -- PHP objects have a mixture of C++ and Java, making them a little different than what you might be used to. In any case, let's get started with the basics.

The What and Why of Objects

For those of you without much experience in object oriented programming, you may be asking yourself, what exactly is an object and why is it useful? The best answer that I have heard describing an object is simply a "black box" that serves a function or functions. What is a "black box?" What I mean is that a "black box" is a chunk of code which is completely independent of any other code -- it takes in information, processes it, and returns a result. You, as the developer, do not need to know anything whatsoever regarding the internal workings of the code. Furthermore, objects are extendable, allowing developers to build off of already-existing code.

I know all of the above might be a lot to take in at once (and we haven't even discussed everything yet). Don't worry! I'll be discussing more on the things I've touched on above in the future, when it'll make much more sense. Thankfully, there is a lot that can be understood just by being walked through the basic syntax, so let's take a look.

Programming PHP

Related Reading

Programming PHP
By Rasmus Lerdorf, Kevin Tatroe

Simple Class Syntax in PHP

The basic syntax in PHP object-oriented programming is basically the same as in a language such as Java. Classes (the code that creates an "object") are defined by the class keyword. Here's an example of a class with nothing inside of it:

<?php

class empty {

/* Member functions and variables go here */

}

?>

Member Variables and Creating an Instance

Of course, a class that has nothing inside of it isn't useful. For a class to be of any use, we'll need to add some functions and member variables. Let's start by adding the variable $foo to our class, renaming the class to foo_object, and, just to make things interesting, let's also set the value of $foo to the string value bar:

<?php

class foo_object {

var $foo = 'bar';

}

?>

Now that we have a class with something inside of it, how do we actually get at and work with this data? To create an object (also known as an instance of a class) you'll need to be introduced to another keyword -- the new keyword. Here's an example where we'll create a new object $myobject that is an instance of our example class foo_object:

<?php

$myobject = new foo_object();

?>

When the PHP engine encounters this statement, it searches for a definition of the foo_object class. Since we have already defined it, the engine creates a working copy of this class and stores the reference to it in the variable $myobject. This means that through the variable $myobject, you can now access any variables or functions that existed within the definition of the foo_object class. For instance, if we wanted to work with the $foo variable inside of this particular instance of foo_object, we could do so as follows:

<?php

            // Set the value of the $foo variable inside of

            // $myobject to 5

$myobject->foo = 5;

// Echo the value of the $foo variable

echo $myobject->foo; // Prints '5' to the browser

?>

Member Functions and the $this Reference Variable

Please note that, at least by convention, developers rarely access member variables directly. Rather, it is the job of the class to provide functions that modify any member variables that the developer may need to modify. With that said, let's create a new class, counter, that creates two member variables, $step and $count, and member functions to work with them.

<?php

class counter {
     var $step;
     var $count; 

     function getcount() {
          return $this->count;
     }
 
     function getstep() {
          return $this->step;
     }

     function changestep($newval) {
          if(is_integer($newval))
          $this->step = $newval;
     }

     function step() {
          $this->count += $this->step;
     }

     function reset() {
          $this->count = 0;
          $this->step = 1;
     }
}
?>

Now, let's take a look at what is really involved in the example above. First, we declare the two member variables $step and $count, which you have already seen in prior examples. Next, we begin the creation of five functions: getcount(), getstep(), changestep(), reset(), and step(). The code contained within these functions is very simple, but there is one thing that probably seems a bit alien -- the use of the seemingly-undeclared variable $this. The variable $this is available from anywhere within any PHP class and is created by PHP when an instance of the class is created. Basically, the $this variable is a reference to the created instance itself, just as $myobject was a reference to the foo_object class. As you can see through the use of the $this variable, you can access variables within an instance of a class, from within the instance itself.

Now that we are dealing with functions, let's take the example class we have created above and put it to a semi-useful purpose.

Also in PHP Foundations:

Using MySQL from PHP, Part 2

Using MySQL from PHP

MySQL Crash Course, Part 3

MySQL Crash Course, Part 2

MySQL Crash Course

<?php

$ticker = new counter();

$ticker->reset();

            $ticker->changestep(2); 

            while($ticker->getcount() <= 20) {

echo "The value of the ticker is " .

                        $ticker->getcount()."<BR>";

$ticker->step();

}

?>

Can you follow the code above, looking at the class definition? First, we create an instance of the class and store a reference to it in the variable $ticker. Next, we call the member function reset(), which resets the counter to its original state and sets the step-count to 2 (meaning that it will count by twos). Then, we loop until the ticker has reached the value of 20. The result will be the following output:

The value of the ticker is 0

The value of the ticker is 2

The value of the ticker is 4

...

The value of the ticker is 20

More to Come

Now that I've covered the very basics of object-oriented programming in PHP, I suggest you work with them a bit and make sure you understand them completely before moving on! In my next column, I'll be discussing some more advanced topics, including object inheritance, special member functions, and more!

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Discuss this article in the O'Reilly Network PHP Forum.

Return to the PHP DevCenter.

Copyright © 2009 O'Reilly Media, Inc.