Jump to content

Problem with function


Lassie

Recommended Posts

I have a function that needs to return a value and it isn’t.I think it’s a scope issue but can’t solve it.

The function is

function is_connected()
  {
    $addr= 'www.google.com';
    if (!$socket = @fsockopen($addr, 80, $num, $error, 5)){
      $connection = 0;
   }else {
      $connection = 1;
   {
      return $connection;
  }
is_connected()
echo $connection;

The function works, but I do get a warning $connection not defined and I don’t get a value.

Any help appreciated.

Link to comment
Share on other sites

1 . Get rid of the @ sign.  Proper coding and handling of any errors is way better than suppressing the error.  You shouldn't have an error that you don't handle.

2 - To get a return value you have to CATCH it.  You do that by:

     $result = is_connected();

    Note: you don't need the argument of $connection in the function header.  Although - you may need something to define/handle $num and $error.

Edited by ginerjm
Link to comment
Share on other sites

My code was just to get an output to print that represents the return value. I was guessing you had that for debugging purposes. You don't need to pass $connection. If you want the return value in a variable to use outside the function the use ginerjm's suggestion and print/use $result.

Link to comment
Share on other sites

Right. You assign the return value of the function to a  variable. A more explicit version of ginerjm's example:

$connection = is_connected();
echo $connection;

See the difference in what you typed and your second block of code in your first post?

Link to comment
Share on other sites

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.