7

Hey guys,

I just wanted to let everyone know that functions can be used very constructively and there are more to them then most think.

Okay this example function is actually pulled from a class of mine so it would probably make more sense in my class but it should make sense anyway.

Right we should all know how to make functions, for those of you that don't I'm going to explain the process.

First off, a function will contain a method or a block of code that we may want to call several times further along in our script. The advantage of adding the block to a function is that we can minimize (so to speak) our code and instead of calling this every time we need to retrieve certain information we use a simple one line call to our function.

Extensive code (padded out a little)

<?php

  $userid = "RANDOM_ID";
  $query = mysql_query("SELECT * FROM `posts` WHERE `auth_id` = '$userid'");
  if( @mysql_num_rows( $query ) > 0 ) {
    while( $row = mysql_fetch_object( $query ) ) {
      echo '<div><a href="http://siteaddress.com/viewpost.php?id=' . $row->id . '">' . $row->title . '</a> Last post on ' . date( "Y-m-D" , $row->time ) . '</div>';
    }
  } else {
    echo "This user hasn't ever made a post.";
  }

?>

Okay so that as you can see is a fair amount of code to have to write every 5-10mins, so we need to simplify this:

<?php

function get_posts() {
  $userid = "RANDOM_ID";
  $query = mysql_query("SELECT * FROM `posts` WHERE `auth_id` = '$userid'");
  if( @mysql_num_rows( $query ) > 0 ) {
    while( $row = mysql_fetch_object( $query ) ) {
      echo '<div><a href="http://siteaddress.com/viewpost.php?id=' . $row->id . '">' . $row->title . '</a> Last post on ' . date( "Y-m-D" , $row->time ) . '</div>';
    }
  } else {
    echo "This user hasn't ever made a post.";
  }
}

?>

Now we have wrapped this code block in the functions brackets everything that is inside of those brackets is going to be called every time we write get_posts(); on our page.

Although this is great it's not very constructive yet. For instance the code above will only get the posts for one user. So if we needed this function for 150 users we would need to rewrite this function 150 times. Not fun.

So what we can do to get around this is adding a parameter to the function:

<?php

function get_posts( [b]$user_id[/b] ) {

}

?>

So now when we call the function we can call it with the user who we wish to retrieves ID and then the function should work with all of our users, there is one more change we need to make though.

<?php

function get_posts( $user_id ) {
  $userid = [b]$user_id[/b];
  $query = mysql_query("SELECT * FROM `posts` WHERE `auth_id` = '$userid'");
  if( @mysql_num_rows( $query ) > 0 ) {
    while( $row = mysql_fetch_object( $query ) ) {
      echo '<div><a href="http://siteaddress.com/viewpost.php?id=' . $row->id . '">' . $row->title . '</a> Last post on ' . date( "Y-m-D" , $row->time ) . '</div>';
    }
  } else {
    echo "This user hasn't ever made a post.";
  }
}

?>

So in order for us to call this function for a user with the user id that is 123456 we would call get_posts( 123456 ) an the function would echo out all of the posts they have made.

So thats pretty neat but there is more. Right say we have put this function in to production and it is in maybe 20-30 scripts on our live site but we want to change this function to include another parameter to control whether or not we want the title of the posts or the number of the posts, now as some of you may know adding another variable/parameter to the function will cause those without the second parameter to call errors. However there is a simple method to get around this problem.

<?php

function get_posts( $user_id , [b]$number=false[/b] ) {

}

?>

Because we have added the =false to the end of our newly added parameter we are essentially saying this parameter doesn;t have to be submitted. Okay so here's how we could implement this into our function.

<?php

function get_posts( $user_id , $number=false ) {
  $userid = $user_id;
  $query = mysql_query("SELECT * FROM `posts` WHERE `auth_id` = '$userid'");
  if( @mysql_num_rows( $query ) > 0 ) {
   [b] if( $number = true ) {
      echo mysql_num_rows( $query );
    } else {[/b]
      while( $row = mysql_fetch_object( $query ) ) {
        echo '<div><a href="http://siteaddress.com/viewpost.php?id=' . $row->id . '">' . $row->title . '</a> Last post on ' . date( "Y-m-D" , $row->time ) . '</div>';
      }
    [b]}[/b]
  } else {
    echo "This user hasn't ever made a post.";
  }
}

?>

So now if we call the function with only the first parameter we will get a list of posts by the user, however if we include the second parameter the we will get the number of posts the user has posted. So this is just a few methods of using functions.

Another point I'd like to make about functions us the global keyword. Some of you may have noticed that if you use a variable from outside of the function then the value is false or it is empty. The way in which we would get around this is by declaring it as global.

<?php
$some_variable = "some_value";
function some_function() {
  echo $some_variable;
}
some_function(); // Wouldn't return anything.

function some_function() {
  global $some_variable;
  echo $some_variable;
}
some_function(); // Would return "some_value"
?>

So I hope you have either learned more about functions or better understand them from reading this little article.

Thanks for reading.

Votes + Comments
Nicely written, thanks.
6
Contributors
5
Replies
41
Views
8 Years
Discussion Span
Last Post by coreyavis
-1

Pls send me a func 2 display date & time 2 use on my code. And also d 1 2 convert a web application 2 pdf format.

0

Hey,
Even though it was a short description, the kind of expression was cute.Good Work...

0

and once you've got a bunch of functions you want to move them into one(or maybe 2) external function libraries, so you don't have to update the same function in multiple files if you need to update the function later.

by the way you have some bold tags mixed in with your code that would probably cause errors if copied and pasted.

1

When creating functions you shouldn't echo out data from within the function, but instead return the data and echo out the returned results.

<?php
    function get_posts( $user_id ) {
        $userid = [b]$user_id[/b];
        $query = mysql_query("SELECT * FROM `posts` WHERE `auth_id` = '$userid'");
        if( @mysql_num_rows( $query ) > 0 ) {
            while( $row = mysql_fetch_object( $query ) ) {
                return '<div><a href="http://siteaddress.com/viewpost.php?id=' . $row->id . '">' . $row->title . '</a> Last post on ' . date( "Y-m-D" , $row->time ) . '</div>';
            }
        } else {
            return "This user hasn't ever made a post.";
        }
    }
?>



echo get_posts(1);
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.