PhpTips.im - Everything about php - Download CMS, find tips and tricks, code snippetz, classes and more and more...
Bookmark this page !
   

Articles

    Home » Articles » PHP Classes » Introduction to PHP Classes (OOP)
Published on : 05.05.2010 Category : PHP Classes Viewed : 56 times.

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:

Code:

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

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

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.

Code:

<?
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:

Code:

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.
Code:

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.

Code:

// 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:

Code:

// 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

Code:

<? 
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:
Code:

$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:

Code:

$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.

Code:

$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.

Code:

$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:
Code:

$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.




Add this article in :

 

There is not yet any comment !



240 Rating: 6.0/10 (1 vote cast)

 

 Members
Log In !
Email Address :

Password :


Change my passowrd !
Sign Up !
We have : 3 members.
Latest member : albans
 
 Last Posts
 
 Advertising
 
©PhpTips.im 2010
Powered by PikaCMS.
Quick Links :
Home | Browse all articles | Downloads | Terms of Use
RSS RSS 2.0 : Articles | Downloads ATOM : Articles | Downloads