I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}
Related
I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}
I'm working on a WordPress shortcode plugin, so I need to define a function to use with add_action('wp_footer', 'fnc_name') for example. I have created the plugin as a class with public functions and static variables.
Here's an example of what I'm trying to do (use $count in the local function tryToGetIt):
class Test {
public static $count;
public function now () {
if (!$this::$count) {
$this::$count = 0;
}
$this::$count++;
$count = (string) $this::$count;
echo 'count should be '.$count;
function tryToGetIt() {
global $count;
echo 'count is '.$count;
}
tryToGetIt();
}
};
$test = new Test();
$test->now();
You can see the demo on IDEONE: http://ideone.com/JMGIFr
The output is 'count should be 1 count is ';
As you can see I've tried declaring the $count variable with global to use the variable from the outer function, but that is not working. I've also tried $self = clone $this and using global $self within the local function.
How can the local function use the variables from within the class's public function?
This is not possible with global. PHP has exactly two variable scopes: global, and local.
<?php
$foo = 'bar'; // global scope <-----------
\
function x() { |
$foo = 'baz'; // function local scope |
|
function y() { |
global $foo; // access global scope /
echo $foo;
}
y();
}
x(); // outputs 'bar'
You COULD try a closure, e.g.
function foo() {
$foo = 'bar';
$baz = function() use (&$foo) { ... }
}
There is no practical way to access a scope defined at some intermediate level of a function call chain. You only ever have the local/current scope, and the global scope.
You could do:
function tryToGetIt($count) {
echo 'count is '.$count;
}
tryToGetIt($count);
Or to select the static variable use:
Test::$count within the tryToGetIt() function.
I tried this code, which works
class Test {
public static $count;
public function now () {
if (!$this::$count) {
$this::$count = 0;
}
$this::$count++;
$count = (string) $this::$count;
echo 'count should be '.$count;
function tryToGetIt() {
echo 'count is '. Test::$count;
}
tryToGetIt();
}
};
$test = new Test();
$test->now();
But I'm not sure I understand why you are trying to do this. Why not make tryToGetIt() a private function within Test rather than nested within now()?
Is there a way to achieve the following in PHP, or is it simply not allowed? (See commented line below)
function outside() {
$variable = 'some value';
inside();
}
function inside() {
// is it possible to access $variable here without passing it as an argument?
}
note that using the global keyword is not advisable, as you have no control (you never know where else in your app the variable is used and altered). but if you are using classes, it'll make things a lot easier!
class myClass {
var $myVar = 'some value';
function inside() {
$this->myVar = 'anothervalue';
$this->outside(); // echoes 'anothervalue'
}
function outside() {
echo $this->myVar; // anothervalue
}
}
Its not possible. If $variable is a global variable you could have access it by global keyword. But this is in a function. So you can not access it.
It can be achieved by setting a global variable by$GLOBALS array though. But again, you are utilizing the global context.
function outside() {
$GLOBALS['variable'] = 'some value';
inside();
}
function inside() {
global $variable;
echo $variable;
}
No, you cannot access the local variable of a function from another function, without passing it as an argument.
You can use global variables for this, but then the variable wouldn't remain local.
It's not possible. You can do it by using global. if you just only do not want to define the parameters but could give it inside the function you can use:
function outside() {
$variable = 'some value';
inside(1,2,3);
}
function inside() {
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
for that see the php manual funct_get_args()
You cannot access the local variable in function. Variable have to set as global
function outside() {
global $variable;
$variable = 'some value';
inside();
}
function inside() {
global $variable;
echo $variable;
}
This works
I know I can use $GLOBALS['var'] inside a function to refer to variables in the global scope.
Is there anyway I can use some kind of a declaration inside the function so I will be able to use $var without having to use $GLOBAL['var'] every time?
Joel
Although it's not recommended, but if you do want to, here's what you can do:
If you only want to GET the values from the vars (and not SET the values), just use extract:
extract($GLOBALS);
This will extract and create all the variables in the current scope.
How about using static class?
such as
class example
{
public static $global;
public static function set($arr)
{
foreach ($arr as $key=>$val)
{
self::$global[$key] = $val;
}
}
}
function example_function()
{
var_dump( example::$global );
}
example::set( array('a'=>1, 'b'=>2) );
example_function();
You can use the global keyword, So you can use type $var instead of $GLOBALS['var'] inside a function.
function myFunc() {
global $var;
$var = 3;
}
$var = 1;
myFunc();
echo $var;
Output: 3
Consider the following situation
file: ./include/functions/table-config.php
containing: .
.
$tablePages = 'orweb_pages';
.
.
file: ./include/classes/uri-resolve.php
containing: class URIResolve {
.
.
$category = null ;
.
.
function process_uri() {
...
$this->category = $tablePages;
...
}
.
.
}
file: ./settings.php
containing: .
.
require_once(ABSPATH.INC.FUNC.'/table-config.php');
require_once(ABSPATH.INC.CLASS.'/uri-resolve.php');
.
.
Will this work. I mean will the access to $tablePages from process_uri() be acceptable or will it give erronous results.
Please suggest corrections or workarounds if error might occur.
Use the global keyword:
In the file where you're assigning the value.
global $tablePages;
$tablePages = 'orweb_pages';
And in the other file:
class URIResolve {
var $category;
function process_uri() {
global $tablePages;
$this->category = $tablePages;
}
}
Also, all global variables are available in the $GLOBALS array (which itself is a superglobal), so you can access the global variable anywhere without using the global keyword by doing something like this:
$my_value = $GLOBALS['tablePages'];
This also serves to make it harder to accidentally overwrite the value of the global. In the former example, any changes you made to $tablePages would change the global variable. Many a security bug has been created by having a global $user and overwriting it with a more powerful user's information.
Another, even safer approach is to provide the variable in the constructor to URIResolve:
class URIResolve {
var $category;
function __construct ($tablePages) {
$this->category= $tablePages;
}
function process_uri() {
// Now you can access table pages here as an variable instance
}
}
// This would then be used as:
new URIResolve($tablePages);
Use a global (not recommended), a constant or a singleton configuration class.
Simply including
$tablePages = 'orweb_pages';
will give your variable local scope so it won't be visible inside other classes. If you use a constant:
define('TABLE_PAGES', 'orweb_pages');
TABLE_PAGES will be available for read access throughout the application regardless of scope.
The advantage of a constant over a global variable is that you dont have to worry about it being overridden in other areas of the application.
<?php
//Use variable php : $GLOBALS in __construct
$x = "Example variable outer class";
class ExampleClass{
public $variables;
function __construct()
{
$this->variables = $GLOBALS; //get all variables from $GLOBALS
}
// example get value var
public function UseVar(){
echo $this->variables['x']; // return Example variable outer class
}
// example set value var
public function setVar(){
$this->variables['x'] = 100;
}
}
echo $x // return Example variable outer class;
$Example = new ExampleClass();
$Example->UseVar(); // return Example variable outer class
$Example->setVar(); // $x = 100;
// or use attr variables
echo $Example->variables['x']; // 100
$Example->variables['x'] = "Hiii";
?>