How to use the class function variable in a local function

advertisements

I'm working on a WordPress shortcode plugin, so I need to define a function to use with add_action('wp_footer', 'fnc_name') for example. I have created the plugin as a class with public functions and static variables.

Here's an example of what I'm trying to do (use $count in the local function tryToGetIt):

class Test {

    public static $count;

    public function now () {
        if (!$this::$count) {
            $this::$count = 0;
        }
        $this::$count++;

        $count = (string) $this::$count;

        echo 'count should be '.$count;

        function tryToGetIt() {
            global $count;
            echo 'count is '.$count;
        }
        tryToGetIt();
    }
};

$test = new Test();
$test->now();

You can see the demo on IDEONE: http://ideone.com/JMGIFr

The output is 'count should be 1 count is ';

As you can see I've tried declaring the $count variable with global to use the variable from the outer function, but that is not working. I've also tried $self = clone $this and using global $self within the local function.

How can the local function use the variables from within the class's public function?


I tried this code, which works

class Test {

    public static $count;

    public function now () {
        if (!$this::$count) {
            $this::$count = 0;
        }
        $this::$count++;

        $count = (string) $this::$count;

        echo 'count should be '.$count;

        function tryToGetIt() {
            echo 'count is '. Test::$count;
        }
        tryToGetIt();
    }
};

$test = new Test();
$test->now();

But I'm not sure I understand why you are trying to do this. Why not make tryToGetIt() a private function within Test rather than nested within now()?