PHP
  Home arrow PHP arrow Introduction to PHP Classes (OOP)
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Introduction to PHP Classes (OOP)
By: Eric 'phpfreak' Rosebrock
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 17
    2003-04-22

    Table of Contents:
  • Introduction to PHP Classes (OOP)
  • The Summary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Introduction to PHP Classes (OOP)


    (Page 1 of 2 )

    Eric has create an article to help our readers learn how to correctly use object orientativity in PHP by the use of PHP classes.

    When you start working with PHP, you'll find that there's many common tasks that you constantly have to type the same code for. Some of you may have figured out by now that making those tasks into a function will save you a little bit of time when you want to reuse that code. You simply declare a function and tell that function what information you want it to use by a method similar to this:

    function MyFunction($variable){
         // Manipulate $variable here:
         echo $variable;
    }

    And then you'd call the function when you needed it:

    MyFunction("Hi, my name is phpfreak");

    and the function would simply echo "Hi my name is phpfreak"

    Well, after awhile you may start to pack around quite a few functions that you have brewed up yourself. Using PHP's Classes, you can start to put those functions into "containers" where they are stored and utilized. PHP's Classes have been proven to be valuable, if you plan and code them properly.

    During this tutorial, I'm going to give you a slight introduction to a Class and give you some practical uses for them. Hopefully after you are done with this tutorial, you'll start to think of ways to implement your own classes and cut your development time considerably on future projects.

    The Class Structure

    When you think of classes, I would almost encourage you to think of "back-end" Your code will be stored in the back-end of your website and the front-end will contain a very clean set of code that is easy to understand. If you put all of the complicated routine tasks into your class, then your script that is utilizing that class will be easier to understand because it will have a cleaner look. That's not the only reason you would use a class, but that's one reason I use them.

    Alright, let's take a look at a class.

    <?
    class MyClass{
        var $email;
        // use a function without variables
        function check_email(){ 
            if(ereg("
    ^.+@.+\..+$
    ", $this->email)) 
                return (true); 
            else
                return (false); 
        }
        // Use a function with variables
        function image_strip($somehtml){
            $somehtml = preg_replace("/(<img)(.*?)(>)/si", "", $somehtml);
            return $somehtml;
        }
    }
    ?>

    The above class was derived from functions that I have found in our QuickCode Library. It's a very simple class to use and we'll break it down into pieces so that you can understand what's going on here.

    First, you need to declare a class:

    class MyClass{

    We are going to create some vars that may be used in any of the functions inside this class without requiring you to specify them for each function. We do this by "var $varname" see below for our $email example we'll use.

    var $email;

    Next, let's take a look at the first function. The function below is a simple email validator. It looks for text on either side of the "@" symbol which is the structure of an email address. This function will take the $email var that we define in our script that calls the class and checks it for validity. If the email address passes the check, we'll return "TRUE" or we'll return "FALSE" if it fails. I'll explain that a little later.

    // use a function without variables
        function check_email(){ 
            if(ereg("
    ^.+@.+\..+$
    ", $this->email)) 
                return (true); 
            else
                return (false); 
        }

    Looking at the function above, notice that I used "$this->email" $this-> is a special constructor that points internally into the class to a variable or another function. When we defined var $email above, we now have $this->email. You'll see how to assign a value to $this->email when we actually use the script that calls the class.

    Note: you can also use other functions inside the same class within other functions. Just use $this->function_name($vars); and other functions within the same class can utilize each other.

    To give you an example that you can put just about anything you want in a class, we've made this a "general purpose" class with multiple different uses. Below, you'll see a function that I have included in this class that strips an image tags out of a string. I also wanted to show you this class because it's a different method of calling the function, this function defines that it will accept one variable and must have that variable defined when you call it. Again, I'll explain that later. See the function below:

    // Use a function with variables
        function image_strip($somehtml){
            $somehtml = preg_replace("/(<img)(.*?)(>)/si", "", $somehtml);
            return $somehtml;
        }
    }

    Now, we just close out our class and we're ready to put it to use!

    Let's name this file as "clsMyClass.php".

    Using the Class in Your PHP Scripts

    The first thing we have to do is include the class. There's not a whole lot to it, just include it by using

    <? 
    include "clsMyClass.php";

    Nowe we can start the fun stuff :) We have our class included and we have to initalize the object by giving it a named variable. See how below:

    $myclass = &New MyClass;

    We have made an object called $myclass and now we can access the items inside the MyClass class that we previously made. So, first thing is first. We've got that "var $email" hanging out in MyClass and we're going to assign a value to it. Let's do this:

    $myclass->email = "you@somewhere.com";

    Keep in mind, you can do $myclass->email = $_POST['email']; or whatever you want to do with it.

    Let's run the email_check function inside the MyClass class.

    $check_email = $myclass->check_email();
    if(!$check_email){
        echo "The email address is not valid!";
    } else {
        echo "The email address is valid!";
    }

    We've simply assigned a variable to the check_email() function and then did some error checking based on that variable. Remember what I said before that if the check_email returns TRUE the $email we told it to check passed the test, and if it failed, it would return FALSE.

    Looking at the if statement above, you'll see that if an "!" or "Error" on the $check_email string is detected, we'll echo "The email address is not valid!", otherwise we'll echo "The email address is valid!".

    Let's take a look at how to use the image_strip function. First, we'll create a string with some HTML inside of it.

    $oldhtml = '<strong>I have an image here: <img src="/myimage.jpg" height="100" width=" 200" ALT="My Image">';

    Now that we have $oldhtml and we know it has an image inside the HTML, let's strip that image out and return the results:

    $newhtml = $myclass->image_strip($oldhtml);
    echo "Here is my old html $oldhtml <br /><br />";
    echo "Here is my new html $newhtml <br /><br />";


    When you take a look at $oldhtml and $newhtml, you should see that the image was stripped out succesfully.

    If you understand what's going on by now, then congratulations, you have just learned the basics of classes! If not, I encourage you to read this tutorial again. It will eventually come to you.

    Let's summarize this introduction to classes on the next page.

    More PHP Articles
    More By Eric 'phpfreak' Rosebrock


     

    PHP ARTICLES

    - Making Usage Statistics in PHP
    - Installing PHP under Windows: Further Config...
    - File Version Management in PHP
    - Statistical View of Data in a Clustered Bar ...
    - Creating a Multi-File Upload Script in PHP
    - Executing Microsoft SQL Server Stored Proced...
    - Code 10x More Efficiently Using Data Access ...
    - A Few Tips for Speeding Up PHP Code
    - The Modular Web Page
    - Quick E-Commerce with PHP and PayPal
    - Regression Testing With JMeter
    - Building an Iterator with PHP
    - PHP Frontend to ImageMagick
    - Using PEAR's mimeDecode Module
    - Incoming Mail and PHP






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT