Create Superglobal Variables in PHP

create superglobal variables in php?

Static class variables can be referenced globally, e.g.:

class myGlobals {

static $myVariable;

}

function a() {

print myGlobals::$myVariable;

}

custom super global in PHP

Sadly there is no way to define superglobals.

(There is no mechanism in PHP for user-defined superglobals.)

Source

Turn on/off PHP making superglobal array elements available as global variables

This can be turned on via register_globals in your php.ini file. However this is deprecated as of 5.3. See the docs.

Warning This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED
as of PHP 5.4.0.

Can we create a Superglobal Boolean variable in php that can be manipulated from any php script?

Solution 1 - Environment Variables

What you might need is something which is present system-wide.
the first thing that came to my mind is environment variables. You can read and write them as needed. you can check them at any point, but it will be visible to other applications as well.

  • http://php.net/manual/en/function.putenv.php

  • http://php.net/manual/en/function.getenv.php

The problem with session is that sessions are closely related to the requests. basically, the session gets started when the request arrived, and they are supposed to get destroyed when the request is over (in the sense that like the user has logged in or logged out)

But the question is about a cron job, which is basically a cli program. which don't have any requests associated with it.

Solution 2 - File Based

By having a file-based check, you can create a file, and add the flag inside file. or the file itself can be the flag.

Solution 3 - By using a datastore

If you have something like a Redis system running as part of the application, you can use this to store the flag/condition.

How to declare a global variable in php?

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);


Related Topics



Leave a reply



Submit