unable to call global variables inside a function class - php

I am new to PHP5 and classes, am struggling with being able to get global variable to work when inside a function, to better explain it please check the code bellow.
class alpha{
#first function
public function n_one(){
#variable
$varr = 1;
#inner function
function n_two(){
global $varr;
#Unable to get variable
echo $varr;
if($varr)
{
echo 'yessssss';
}
}
echo $varr // Returns variable fine
}
}
I seem to be doing something wrong violating how classes and functions work, can't figure what is it.

Move the 'inner function', and the property.
class Alpha
{
private $varr = 1;
public function n_one()
{
// to access a property ore another method, do this
$this->varr = $this->doSomething();
return $this->varr; // Returns variable fine
}
private function doSomething()
{
// manipulate $this->varr here
}
}
Also, don't ever echo from within the class, instead return the variable and echo it.
echo $alpha->n_one();

global means to access the variable in the global scope, not just the containing scope. When you refer to $varr in the inner function it's treated as $GLOBALS['varr'].
If you want it to refer to the same variable as in the outer function you need to declare the variable global there as well. Otherwise it's a local variable in that function, while the inner function accesses the global variable.
#first function
public function n_one(){
global $varr;
#variable
$varr = 1;
#inner function
function n_two(){
global $varr;
#Unable to get variable
echo $varr;
if($varr)
{
echo 'yessssss';
}
}
echo $varr // Returns variable fine
}
Alternatively you can use the use() declaration to declare a variable that should be inherited from the outer scope.
#inner function
function n_two() use($varr) {
global $varr;
#Unable to get variable
echo $varr;
if($varr)
{
echo 'yessssss';
}
}

Related

Global variable in sub-function no need to declare

whether to do a declare variable when a variable is in a sub-function ?
Like the example carried this:
function cobasaja(){
global $coba;
return $coba;
}
function ditampilkan(){
global $coba;
$coba = "content trying...";
return cobasaja();
}
echo "View: ".ditampilkan();
Why it can not be like this:
function cobasaja(){
global $coba;
return $coba;
}
function ditampilkan(){
//global $coba; <= not declare in viewer function
$coba = "content trying...";
return cobasaja();
}
echo "View: ".ditampilkan();
But the second experiment did not work.
Because as I recall, usually the second way can be done, but now I do it can not, is this because of its PHP version or setting in PHP.ini ?
Adding a function creates a new scope. Any variables you want to use in the function need to be either defined in that scope, brought in from the outer scope with global, or passed in as parameters. This general concept has not changed much over PHP versions as far as I know, so I don't believe your second experiment would have worked in an earlier PHP version, or could work by changing a configuration setting.
If your functions are in the same class, you can use object properties rather than global variables to achieve something like what you want.
class Example {
private $coba = '';
protected function cobasaja() {
return $this->coba;
}
public function ditampilkan() {
$this->coba = "content trying...";
return $this->cobasaja();
}
}

global variable can't accessible inside the function

I need to access the global variable from another function. First I have assigned the value to global variable in one function. When I am trying to get that value from another function, it always returns null. Here my code is
StockList.php
<?php
$_current;
class StockList
{
public function report(){
global $_current;
$_current = 10;
}
public function getValue(){
print_r($GLOBALS['_current']);
}
}
?>
Suggestion.php
<?php
include ("StockList.php");
$stk = new StockList();
$stk->getValue();
?>
Thanks in advance.
Man, its hard to understand what are you trying to do as you said you have called report() in your index.php
Anyways, when dealing with classes, to set variable values, standard procedure is as following:
class StockList
{
public $_current;
public function setValue($value){
$this->current = $value;
}
public function getValue(){
return $this->current;
}
}
And after whenever you wanna use the class:
<?php
include ("StockList.php");
$stk = new StockList();
$stk->setValue(10);
$_current = $stk->getValue();
var_dump($_current);
?>
This is basic idea of OOP, benefits of this approach are:
You can dynamically set value of $_current.
Your getValue() function is not dedicated for printing the value of the variable, thats why you can use that function only for getting the value and then do whatever you want with it.

How to use class function variable within a local function

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

Declaring a global variable inside a function

I have two PHP files. In the first I set a cookie based on a $_GET value, and then call a function which then sends this value on to the other file. This is some code which I'm using in join.php:
include('inc/processJoin.php');
setcookie("site_Referral", $_GET['rid'], time()+10000);
$joinProc = new processJoin();
$joinProc->grabReferral($_COOKIE["site_Referral"]);
The other file (processJoin.php) will then send this value (among others) to further files which will process and insert the data into the database.
The problem I'm having is that when the grabReferral() function in processJoin.php is called, the $referralID variable isn't being defined on a global scale - other functions in processJoin.php can't seem to access it to send to other files/processes.
I've tried this in processJoin.php:
grabReferral($rid) {
global $ref_id;
$ref_id = $rid;
}
someOtherFunction() {
sendValue($ref_id);
}
But the someOtherFunction can't seem to access or use the $ref_id value. I've also tried using define() to no avail. What am I doing wrong?
you have to define the global var in the second function as well..
// global scope
$ref_id = 1;
grabReferral($rid){
global $ref_id;
$ref_id = $rid;
}
someOtherFunction(){
global $ref_id;
sendValue($ref_id);
}
felix
personally, I would recommend the $GLOBALS super variable.
function foo(){
$GLOBALS['foobar'] = 'foobar';
}
function bar(){
echo $GLOBALS['foobar'];
}
foo();
bar();
DEMO
This is a simple and working code to initialize global variable from a function :
function doit()
{
$GLOBALS['val'] = 'bar';
}
doit();
echo $val;
Gives the output as :
bar
The following works.
<?php
foo();
bar();
function foo()
{
global $jabberwocky;
$jabberwocky="Jabberwocky<br>";
bar();
}
function bar()
{
global $jabberwocky;
echo $jabberwocky;
}
?>
to produce:
Jabberwocky
Jabberwocky
So it seems that a variable first declared as global inside a function and then initalised inside that function acquires global scope.
The global keyword lets you access a global variable, not create one. Global variables are the ones created in the outermost scope (i.e. not inside a function or class), and are not accessible inside function unless you declare them with global.
Disclaimer: none of this code was tested, but it definitely gets the point across.
Choose a name for the variable you want to be available in the global scope.
Within the function, assign a value to the name index of the $GLOBALS array.
function my_function(){
//...
$GLOBALS['myGlobalVariable'] = 42; //globalize variable
//...
}
Now when you want to access the variable from code running in the global scope, i.e. NOT within a function, you can simply use $ name to access it, without referencing the $GLOBALS array.
<?php
//<global scope>
echo $myGlobalVariable; //outputs "42"
//</global scope>
?>
To access your global variable from a non-global scope such as a function or an object, you have two options:
Access it through the appropriate index of the $GLOBALS array. Ex: $GLOBALS['myGlobalVariable'] This takes a long time to type, especially if you need to use the global variable multiple times in your non-global scope.
A more concise way is to import your global variable into the local scope by using the 'global' statement. After using this statement, you can reference the global variable as though it were a local variable. Changes you make to the variable will be reflected globally.
//<non global scopes>
function a(){
//...
global $myGlobalVariable;
echo $myGlobalVariable; // outputs "42"
//...
}
function b(){
//...
echo $GLOBALS['myGlobalVariable']; // outputs "42"
echo $myGlobalVariable; // outputs "" (nothing)
// ^also generates warning - variable not defined
//...
}
//</non global scopes>
Please use global variables in any language with caution, especially in PHP.
See the following resources for discussion of global variables:
http://chateau-logic.com/content/dangers-global-variables-revisited-because-php
http://c2.com/cgi/wiki?GlobalVariablesAreBad
The visibility of a variable
I hope that helped
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>

Outer Variable Access in PHP Class

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";
?>

Categories