Jump to content

Recommended Posts

I notice a lot of scripts where the author will create a function that only gets used once.  Why bother?  if it's a one time deal, why not just run the code? I'm looking for the reason.  Is it just to make the code look better?  Does is somehow make the script faster?  Is it just "best practice"?  I'm just trying to learn...

Link to comment
https://forums.phpfreaks.com/topic/51830-solved-when-to-use-functions/
Share on other sites

... any idea how often you write a huge piece of code,and then later discover you need to use it again, so you copy and paste it, and then you realize you need to use it yet again!  >:(

 

Functions are good practice, they are neater, but they wont speed things up or anything.

sometimes run faster, and not always better practice... but it does make programming it faster... for example... every function in itself is a "program"...

 

<?php
function db_connect($host, $username, $password, $database){
global $dblink;
$dblink=@mysql_connect("$host","$username","$password");
$dbdatabase=@mysql_select_db("$database");
if((!$dblink)||(!$dbdatabase)) return false;
register_shutdown_function('db_disconnect');
return true;
}
?>

 

i only use that once on every page, but, as you see... just by db_connect("","","",""); it automatically connects to the host, returns false on error, turns on the db_disconnect, and returns true...

 

i use functions ALOT... but thats just my style... i find that by using functions, i can expand what i'm doing with alot less code...

Functions can help to keep your code cleaner, even if its just because they don't introduce extra variables into the current namespace.

 

Also, sometimes it just easier to put logic into a function.

 

There is no real straight up answer here. IMO, the more code within functions the better, however, I never use functions to output html. My functions always return data to the calling code, which then prints the result. eg;

 

<?php

  function hello() {
    return "Hello world";
  }
  echo hello();

?>

 

Not

 

 

<?php

  function hello() {
    echo "Hello world";
  }
  hello();

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.