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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.