How to create a variable outside function but which should not be visible outside my php file?
I mean a global variable with single file scope. I don't want to add the function name in global namespace which may clash tomorrow.
How to create a variable outside function but which should not be visible outside my php file?
I mean a global variable with single file scope. I don't want to add the function name in global namespace which may clash tomorrow.
You could use an anonymous function:
<?php
$x = function() {
$local_global = "nyah can't access me from outside";
... do your stuff ...
}
$x();
This might be the most inelegant solution ever, but for most cases it can work without having to pass the variable to each function, which is something you don't want to do.
Just create a function that returns the value you need as "global", and call that function whenever you need it. Since you said you want this variable to be accessed only inside ONE php file, just place this defining function there:
function faux_global()
{
$faux_global_var = 'This is supposed to be global';
return $faux_global_var;
}
I want a constant variable to be used by many functions. But it's use is only for my module and should not bother other's code. Actually I'm working on Drupal.
I don't know the requirements of a Drupal module very well, but what you describe sounds like a protected constant or variable. As protected constants do not exist, the only option is to create a protected variable. Just place all your module function code into one or multiple class(es) that have access to a protected member variable and you're fine.
class MyModule
{
protected $variable;
public function myFunction()
{
$this->$variable; # accessible only within MyModule functions.
}
}
A private variable works as well, as long as you only use one class.
with PHP5.2 and below, you simply can't do it. Once it's global, it's global.
but from 5.3 onwards, there is Namespacing, which allows different levels of scope.
see here: http://www.ibm.com/developerworks/opensource/library/os-php-5.3new3/index.html