0

I have 2 php files.

index.php:

<?php
    $counter = 0;
    require_once('temp.php');
    temp();
    echo $counter;
?>

temp.php:

<?php
    function temp() {
            tempHelper();
    }
    function tempHelper() {
            $counter++;
    }
?>

I want to print 1 not 0. I tried to set $counter as global variable without success.

What can I do?

3 Answers 3

2

Your tempHelper function is incrementing a local $counter variable, not the global one. You have to either pass the variable in by reference through both functions, or use the global variable:

function tempHelper() {
  global $counter;
  $counter++;
}

Note that dependence on global variables likely indicates a design flaw in your application.

Sign up to request clarification or add additional context in comments.

6 Comments

Faster than me :) Here is a link php.net/manual/en/language.variables.scope.php
There is not way to set in the initalization of $counter to make him global?
In PHP, there is no way to make user defined super globals. If you are wanting to do this though, reconsider your application design.
I hope you do not ignore all the people advising you not to do this. You shouldn't be using global variables unless you fully understand why they are bad and make a conscious decision to use them anyways.
Why no to use it? Why that are bad thing?
|
1

I would advise against using global variables. Using a class for your counter would probably be better.

class Counter {
    public $counter;

    public function __construct($initial=0) {
        $this->counter = $initial;
    }

    public function increment() {
        $this->counter++;
    }

}

Or just use a variable without a function. Your function seems redundant, since it would be just as easy to type $counter++ than it would the function name.

Comments

0

I suppose this should work:

<?php
    $counter = 0;

    function temp() {
            // global $counter; [edited, no need for that line]
            tempHelper();
    }
    function tempHelper() {
            global $counter;
            $counter++;
    }

    temp();
    echo $counter;
?>

Or you can pass the variable as an argument or return new value from that function.

More info at http://www.simplemachines.org/community/index.php?topic=1602.0

3 Comments

There is no reason to declare global $counter inside temp, which doesn't use it.
I just realized it now. Thanks.
The temp function seems redundant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.