Mr J
Mr J

Reputation: 55

Function wont return a value?

I am trying to set a variable in a function so that when the function is called, it would provide the script with a variable value to inform the page that the function was called. This works just displaying a message:

function MyMessage($display_message)
{
    echo $display_message;
}

That works fine, so when I call up:

MyMessage("Updated Database!");

that works too np. The problem is that the function displays this message before the header file in some pages since the header is at the bottom of the page before it is called. Is it possible to make it like:

function MyMessage($display_message)
{

    $function_ran = 1;

    echo $display_message;

    return $function_ran;

}

Then in the script if I display

if ( $function_ran != 1 )
{
    include("header.php");
}

That way it only displays the header if the function is not ran. The problem is that the $function_ran value is not returned when the function is called. How can I do this?

Upvotes: 0

Views: 75

Answers (6)

Barmar
Barmar

Reputation: 780929

Instead of checking before calling the function, the function could use a static variable to avoid doing its work twice:

function MyMessage($display_message) {
    static $function_ran = false;

    if ($function_ran) {
        return;
    }

    $function_ran = true;
    echo $display_message;
}

Upvotes: 1

DanJ
DanJ

Reputation: 1756

You can store the flag in a global, but to modify the global variable from the function you need to use the global keyword.

Something like:

$function_ran = 0;

function MyMessage($display_message) {
  global $function_ran;

  $function_ran = 1;
  echo $display_message;
}

Upvotes: 0

PersianGulf
PersianGulf

Reputation: 2935

You should use sessions, you should use session handler and use it,you can set a session for return value of this function.

Upvotes: 0

Andreas
Andreas

Reputation: 2678

If you really want to use the return of the function you have to assign the return to a variable like:

$function_ran = MyMessage("Updated Database!");

Of course, it would be possible to make $function_ran global, but than you don't have to use the return.

I would definitely go for the assigning of the return value, because that is more transparent and the better programming style.

Hope that helps

Upvotes: 1

Buddy
Buddy

Reputation: 11028

If you don't want to use globals, you need to store the result of the function:

$function_ran = MyMessage("Updated Database!");
if ( $function_ran != 1 )
{
  include("header.php");
}

Upvotes: 2

John3136
John3136

Reputation: 29265

Make $function_ran a global and ensure you use the global version in the function.

$function_ran = 0;

# stuff

function MyMessage($display_message)
{
    global $function_ran;
    $function_ran = 1;
    echo $display_message;
}

Upvotes: 1

Related Questions