如何在局部函数中使用类函数变量


How to use class function variable within a local function

我正在开发一个WordPress短代码插件,所以我需要定义一个用于add_action('wp_footer', 'fnc_name')的函数。 我已经将插件创建为具有公共函数和静态变量的类。

这是我正在尝试执行的操作的示例(在本地函数tryToGetIt中使用$count):

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();

您可以在IDEONE上看到演示:http://ideone.com/JMGIFr

输出为"计数应为 1 计数为";

如您所见,我尝试使用global声明$count变量以使用外部函数中的变量,但这不起作用。 我还尝试在本地函数中$self = clone $this和使用global $self

局部函数如何使用类的公共函数中的变量?

这在 global 中是不可能的。PHP 正好有两个变量作用域:全局和局部。

<?php
$foo = 'bar'; // global scope  <-----------
                                           '
function x() {                             |
    $foo = 'baz'; // function local scope  |
                                           |
    function y() {                         |  
       global $foo; // access global scope /
       echo $foo;
    }
    y();
}
x(); // outputs 'bar'

您可以尝试关闭,例如

function foo() {
   $foo = 'bar';
   $baz = function() use (&$foo) { ... } 
}

没有实用的方法可以访问在函数调用链的某个中间级别定义的范围。您只有本地/当前作用域和全局作用域。

你可以做:

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

或者选择静态变量,请使用:

Test::$count在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() {
            echo 'count is '. Test::$count;
        }
        tryToGetIt();
    }
};
$test = new Test();
$test->now();

但我不确定我是否理解你为什么要这样做。为什么不让 tryToGetIt() 成为 Test 中的私有函数,而不是嵌套在 now() 中呢?