Access static variable in function from outside

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Thomas Mlynarczyk

    Access static variable in function from outside

    Hello,

    Is there a way to access a static variable defined inside a function from
    outside that function? Something like the following:

    function foo() {
    static $bar = 'stuff';
    // more code
    }

    // Something like this (which will not work, of course):
    echo foo()::bar; // or
    echo foo()->bar;

    Or can the function return a reference to one of its static vars?

    Greetings,
    Thomas




  • Janwillem Borleffs

    #2
    Re: Access static variable in function from outside

    Thomas Mlynarczyk wrote:
    [color=blue]
    > Is there a way to access a static variable defined inside a function
    > from outside that function? Something like the following:
    >
    > function foo() {
    > static $bar = 'stuff';
    > // more code
    > }
    >
    > // Something like this (which will not work, of course):
    > echo foo()::bar; // or
    > echo foo()->bar;
    >
    > Or can the function return a reference to one of its static vars?
    >[/color]

    You could only do this is foo() would be an object, which it isn't.

    What you can do is pass it a variable by reference, which the function
    assigns the static value to:


    function foo($var) {
    static $bar = 'stuff';
    $var = $bar;
    // more code
    }

    $var;
    foo(&$var);

    print $var;

    *or* declare $bar as a global var instead of a static:

    function foo() {
    global $bar;
    $bar = 'stuff';
    // more code
    }

    foo();
    print $bar;


    JW



    Comment

    • Thomas Mlynarczyk

      #3
      Re: Access static variable in function from outside

      Also sprach Janwillem Borleffs:
      [color=blue]
      > What you can do is pass it a variable by reference, which the function
      > assigns the static value to:
      >
      >
      > function foo($var) {
      > static $bar = 'stuff';
      > $var = $bar;
      > // more code
      > }
      >
      > $var;
      > foo(&$var);[/color]

      That looks like what I need.
      Thanks a lot!



      Comment

      Working...