467,104 Members | 1,032 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,104 developers. It's quick & easy.

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


Jul 17 '05 #1
  • viewed: 3176
Share:
2 Replies
Thomas Mlynarczyk wrote:
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?


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

Jul 17 '05 #2
Also sprach Janwillem Borleffs:
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);


That looks like what I need.
Thanks a lot!

Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by pembed2003 | last post: by
49 posts views Thread by Yannick Turgeon | last post: by
9 posts views Thread by AnandRaj | last post: by
12 posts views Thread by codefixer@gmail.com | last post: by
12 posts views Thread by Steve Blinkhorn | last post: by
18 posts views Thread by Jack | last post: by
8 posts views Thread by aarklon@gmail.com | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.