0

Class A has a member with a function:

class A {
    public function foo() {
        static $x=2;
        function bar() {
            echo "x=$x";
        }
        bar();
    }
}
$a = new A();
$a->foo();

This gives an error in line echo "x=$x";.

How to access $x from class member foo() in function bar()?

I'm using PHP 5.5.9.

7
  • Shouldn't that be self::$x? Commented Oct 3, 2017 at 21:53
  • No, that results in FATAL ERROR Cannot access self:: when no class scope is active.... $x is no static class member! Commented Oct 3, 2017 at 21:55
  • 1
    $x is out of scope for bar(). There's several options, here's one of them. Commented Oct 3, 2017 at 21:57
  • Ok, works. Isn't there a direct way to access $x? Commented Oct 3, 2017 at 22:00
  • Define "direct". They're different scopes. Commented Oct 3, 2017 at 22:06

2 Answers 2

2

Don't try to declare your static variables within a function.

class A {
    protected static $x = 2;

    public function foo() {
        function bar() {
            echo "x=" . self::$x;
        }

        bar();
    }
}

$a = new A();
$a->foo();
Sign up to request clarification or add additional context in comments.

13 Comments

Given context it is hard to say if this is the right answer or not. But I would imagine that this scenario (static class property) is more likely what OP wanted to use.
Why not declare static variables inside functions?
This doesn't work. bar() is in the global scope, it can't see $x: Fatal error: Cannot access self:: when no class scope is active in /Applications/MAMP/htdocs/trello/up.php on line 8
I also thought of using the use keyword for function bar(): function bar() use ($x) { .... But use is only available for closures :-( Do we have to wait for a future PHP release?
|
0

Finally found a solution, based on the closure idea of @ishegg:

class A {
    public function foo() {
        static $x=2;
        $bar = function () use (&$x,&$bar) {
            echo "x=$x\n";
            if (++$x<6) $bar();
        };
        $bar();
    }
}
$a = new A();
$a->foo();

This recursion is possible because the closure is passed to itself as reference. And since a reference is just a pointer it can be evaluated before the function is fully defined. So the solution effectively relies on closures passed by reference.

Please note that $x has also be passed to as reference &$x since otherwise we just get a copy of $x and the static variable $x never changes.

Runs like a charm: https://3v4l.org/U293s

Result:

x=2 
x=3 
x=4 
x=5

Comments

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.