How to use class function variable within a local function - php

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()?

Related

How to access PHP variable on every part of a wordpress page? [duplicate]

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';
}

PHP use variable defined outside of function [duplicate]

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';
}

PHP assign a value to a variable (globa) from within the classs

I have a small PHP snippet.
How can I assign a new value to my global from within a main class?
Example:
$GlobalValue = 0;
class SampleModuleController extends SampleController {
public function doSomething() {
$NewValue = 1;
$GlobalValue = $NewValue
}
}
echo $GlobalValue;
//This always echo's 0, When I try to output or print outside the class or use somewhere above in the php code.
//I need to be able to assign the new value from within my class
//and the function doSomething so it should be 1
You can pass parameter as reference in the method doSomething() and then call that function passing your variable $GlobalValue. However it's not very recommended to have global variables. You should consider change your code to more OOP.
$GlobalValue = 0;
class SampleModuleController {
private $newValue = 3;
public function doSomething(&$variable) {
$variable = $this->newValue;
}
}
$ModuleController = new SampleModuleController();
$ModuleController->doSomething($GlobalValue);
echo $GlobalValue; //print 1
If i understood it right what you are trying to do can be achieved quite easily with this:
global $GlobalValue;
$GlobalValue = 0;
class SampleModuleController {
public function doSomething() {
global $GlobalValue;
$NewValue = 1;
$GlobalValue = $NewValue;
}
}
$ModuleController = new SampleModuleController();
$ModuleController->doSomething();
echo $GlobalValue; //print 1
They key is in the "global" keyword (which is the same as accessing the $GLOBAL["your_var_name"] container.
Beside this, as others said relying on global variables should be discouraged.

how to access variables in a class but outside a function?

i made the following code:
<?php
class hoi {
public $a = 1;
function test()
{
echo $this->$a; /* reference to alocal scope variable? */
}
}
$hoi = new hoi;
$hoi->test();
?>
I try to echo $a but this does not work,
how can i echo variables declared inside the class but outside the function?
The syntax is:
$this->a
Using an additional $ in there is a "variable variable" for properties.
class hoi {
public $a = 1;
function test() {
echo $this->a;/* the variable is accessed like this - no need for the $ */
}
}
$hoi = new hoi();/* required as there is no __construct() method */
$hoi->test();

Access local variable in function from outside function (PHP)

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

Categories