Page 1 of 1

returning values from function

Posted: Sat Sep 15, 2007 12:41 pm
by shivam0101
which is the right way of returning values.

Code: Select all

function ReadTemplate($file)
 {
    if(!empty($file) && file_exists($file))
    {
      $fh=fopen($file, 'r');
      $file_read=fread($fh, filesize($file));
      fclose($fh);
      return $file_read;
    }
   else
    {
      return 'Error in reading file';
    }
 }

OR

Code: Select all

function ReadTemplate($file)
 {
    if(!empty($file) && file_exists($file))
    {
      $fh=fopen($file, 'r');
      $file_read=fread($fh, filesize($file));
      fclose($fh);
      $return= $file_read;
    }
     else
     {
      $return= 'Error in reading file';
     }

     return $return;
 }

Posted: Sat Sep 15, 2007 12:47 pm
by s.dot
There is no right way. Whichever way you feel comfortable doing. Personally, I'd prefer the first example.

Re: returning values from function

Posted: Sat Sep 15, 2007 4:12 pm
by superdezign
By standards, you wouldn't have an else statement there at all, so it'd be the first way, just without the 'else' branch.

It'd make more sense to return false or NULL instead of an error message, though.

Posted: Sat Sep 15, 2007 4:24 pm
by jeffery
I normally do it this way:

Code: Select all

function ReadTemplate($file)
 {
    $file_read = '';
    if(!empty($file) && file_exists($file))
    {
      $fh=fopen($file, 'r');
      $file_read=fread($fh, filesize($file));
      fclose($fh);
    }

    return $file_read;
 }

Posted: Sat Sep 15, 2007 11:58 pm
by fly135
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


how about this

Code: Select all

function ReadTemplate($file)
 {
    if(!empty($file) && file_exists($file))
    {
      $fh=fopen($file, 'r');
      $file_read=fread($fh, filesize($file));
      fclose($fh);
      return $file_read;
    }
   
      return 'Error in reading file';
    
 }

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Sun Sep 16, 2007 1:32 am
by Zoxive
Like the others said i would rather return False instead of returning an error message itself, then you can't use it like..

Code: Select all

if(!ReadTemplate($file)){
  // Stuff
}
Because it will always return True.