Jump to content
Lassie

Problem with function

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.

Share this post


Link to post
Share on other sites

You're not assigning the returned value from is_connected() to $connection. You're just calling the function and expecting that $connection has been created elsewhere.

Share this post


Link to post
Share on other sites

Could you expand on your comments please.

If on calling the function I do this:

is 

is_connected($connection)

//and 

funtion is_connected($connection)

I still don’t get a value.

?

Share this post


Link to post
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

Share this post


Link to post
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.

Share this post


Link to post
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?

Share this post


Link to post
Share on other sites

Thanks guys, I now have it working as required.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

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.