By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,722 Members | 1,904 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,722 IT Pros & Developers. It's quick & easy.

Access static variable in function from outside

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
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.