create superglobal variables in php? - php

is there a way to create my own custom superglobal variables like $_POST and $_GET?

Static class variables can be referenced globally, e.g.:
class myGlobals {
static $myVariable;
}
function a() {
print myGlobals::$myVariable;
}

Yes, it is possible, but not with the so-called "core" PHP functionalities. You have to install an extension called runkit7:
Installation
After that, you can set your custom superglobals in php.ini as documented here:
ini.runkit.superglobal

I think you already have it - every variable you create in global space can be accessed using the $GLOBALS superglobal like this:
// in global space
$myVar = "hello";
// inside a function
function foo() {
echo $GLOBALS['myVar'];
}

Class Registry {
private $vars = array();
public function __set($index, $value){$this->vars[$index] = $value;}
public function __get($index){return $this->vars[$index];}
}
$registry = new Registry;
function _REGISTRY(){
global $registry;
return $registry;
}
_REGISTRY()->sampleArray=array(1,2,'red','white');
//_REGISTRY()->someOtherClassName = new className;
//_REGISTRY()->someOtherClassName->dosomething();
class sampleClass {
public function sampleMethod(){
print_r(_REGISTRY()->sampleArray); echo '<br/>';
_REGISTRY()->sampleVar='value';
echo _REGISTRY()->sampleVar.'<br/>';
}
}
$whatever = new sampleClass;
$whatever->sampleMethod();

One other way to get around this issue is to use a static class method or variable.
For example:
class myGlobals {
public static $myVariable;
}
Then, in your functions you can simply refer to your global variable like this:
function Test()
{
echo myGlobals::$myVariable;
}
Not as clean as some other languages, but at least you don't have to keep declaring it global all the time.

No
There are only built-in superglobals listed in this manual

Not really. though you can just abuse the ones that are there if you don't mind the ugliness of it.

You can also use the Environment variables of the server, and access these in PHP
This is a good way to maybe store global database access if you own and exclusively use the server.

possible workaround with $GLOBALS:
file.php:
$GLOBALS['xyz'] = "hello";
any_included_file.php:
echo $GLOBALS['xyz'];

One solution is to create your superglobal variable in a separate php file and then auto load that file with every php call using the auto_prepend_file directive.
something like this should work after restarting your php server (your ini file location might be different):
/usr/local/etc/php/conf.d/load-my-custom-superglobals.ini
auto_prepend_file=/var/www/html/superglobals.php
/var/www/html/superglobals.php
<?php
$_GLOBALS['_MY_SUPER_GLOBAL'] = 'example';
/var/www/html/index.php
<?php
echo $_MY_SUPER_GLOBAL;

Actually, there is no direct way to define your own superglobal variables; But it's a trick that I always do to access simpler to my useful variables!
class _ {
public static $VAR1;
public static $VAR2;
public static $VAR3;
}
Then I want to use:
function Test() {
echo \_::$VAR2;
}
Notice: Don't forget to use \ before, If you want to use it everywhere you have a namespace too...
Enjoy...

Related

How to define/declare a variable in a class such that its accessible in another files in PHP?

I need a variable which remains accessible across all the PHP files am using, i.e, I should be able to read it and change its value.
I tried to declare a class in a file with variable x:
In file1.php
public class sample{
public static $curruser = '0';
public function getValue() {
return self::$curruser;
}
public function setValue($val){
self::$curruser = $val;
}
}
Its being set in file2.php by calling sample::setValue($val). This page has a redirect to file3.php
I need to access this variable file3.php:
include 'file1.php';
print sample::getValue();
This gives me 0 instead of the value I set in file2.php.
Clearly, my understanding of static variables in PHP is a little shaky. Is there a proper way to do set and access the variable across files?
Try to use session or some sort of caching mechanism if you want data to persist between requests.
i recommend defining a constant like this:
define('CONSTANT_NAME' ,$value);
and access the value like this:
echo CONSTANT_NAME;
or using static function and static values and static functions like this:
public static function setValue($val){
self::$curruser = $val;
}
public static function getValue() {
return self::$curruser;
}

Passing variables to an included file

I have a template class which goes like this:
class Template{
public $pageTitle = "";
public function __construct($pageTitle){
$this->pageTitle = $pageTitle;
}
public function display(){
include "/includes/head.php";
include "/includes/body.php";
}
}
Now, I'm used to Java's workings but I don't understand why I'm getting an undefined variable ($pageTitle) error. The included files need to be able to access that variable. I know it's going to be very simple but I actually haven't found out why.
What do I need to do to allow includes to see this variable?
The includes will also have to use $this->pageTitle. Effectively, the include makes them part of the method body.
The included file lives in the same scope as your object. So you need to call:
$this->pageTitle
If you don't want to do the whole $this->, you can do something like the following... The extract function will extract the array $this->data into variables with names respective to the key/index of each item. So now you will be able to do echo $pageTitle;
class Template{
public $data = Array();
public function __construct($pageTitle){
$this->data['pageTitle'] = $pageTitle;
}
public function display(){
extract($this->data);
include "/includes/head.php";
include "/includes/body.php";
}
}
Scope is a little different in PHP than in java.
For your specific case you need
$this->pageTitle
To access a variable declared outside the class, you'll need to make it global
global $myVar;

PHP - accessing global variables in all functions of class

I need to access some variables of an external php file in most of functions of a class. I'm accessing in following way (and it works fine)
class test{
function a(){
global $myglobalvar ;
..
..
}
function b(){
global $myglobalvar ;
..
..
}
function c(){
global $myglobalvar ;
..
..
}
}
Is there a way that i can access $myglobalvar in all functions of the class without declaring in each function? I did read that it can be done by declaring only once in the constructor of the class, but I dont know how to do it.
Thanks for any help.
class test{
private $myglobalvar;
public function __construct($var){
$this->myglobalvar = $var;
}
function a(){
echo $this->myglobalvar;
}
function b(){
echo $this->myglobalvar;
}
function c(){
echo $this->myglobalvar;
}
}
$test = new test("something");
$test->a(); // echos something
$test->b(); // echos something
$test->c(); // echos something
You can create a reference to a global variable in the constructor (much like global would):
class test{
function __construct() {
$this->myglobalvar = & $GLOBALS["myglobalvar"];
Which then allows aceess to the global via $this->myglobalvar in each method.
If you tell us more about this case, we might be able to tell you a better way to solve your problem. Globals should be avoided, whenever possible. Are you really talking about a variable or is it more like a configuration option that stays the same during a whole server roundtrip. In that case you could think of treating it like a configuration option and store it in a registry object (singleton).

alias to include

i have alias to include() in my functions.php file:
function render_template($template)
{
include($template);
}
and simple template.html :
Hello, <?php echo $name ?>
But unfortunately, alias function gave me this output:
require 'functions.php';
$name = "world";
include('template.html'); // Hello, world
render_template('template.html'); // PHP Notice:Undefined variable: name
why is that? and how i can fix this?
thanks.
You have two more options to make it work around the scope issue. (Using global would require localising a long list of vars. Also it's not actually clear if your $name resides in the global scope anyway and always.)
First you could just turn your render_template() function into a name-resolver:
function template($t) {
return $t; // maybe add a directory later on
}
Using it like this:
$name = "world";
include(template('template.html'));
Which is nicer to read and has obvious syntactical meaning.
The more quirky alternative is capturing the local variables for render_template:
$name = "world";
render_template('template.html', get_defined_vars());
Where render_template would require this addition:
function render_template($template, $vars)
{
extract($vars); // in lieu of global $var1,$var2,$var3,...
include($template);
}
So that's more cumbersome than using a name-resolver.
The variable $name is not visible at the point where include is called (inside function render_template). One way to fix it would be:
function render_template($template)
{
global $name;
include($template);
}
Its a Scope Problem, you can set the variable to global, or encapsulate the whole thing a little bit more, for example like that:
class view{
private $_data;
public function __construct(){
$this->_data = new stdClass();
}
public function __get($name){
return $this->_data->{$name};
}
public function __set($name,$value){
$this->_data->{$name} = $value;
}
public function render($template){
$data = $this->_data;
include($template);
}
}
$view = new view;
$view->name = "world";
$view->render('template.html');
template.html :
Hello <?php print $data->name; ?>
If $name is in the global scope then you can get around it by declaring the variable global with the function. But a better solution would be to re-architect the code to require passing the relevant variable value into the function.
This is expected.
Look here.
You would be interested in the following quote, "If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs".

PHP access external $var from within a class function

In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like
class myclass {
bla ....
bla ....
function myfunction() {
if (isset($some_external_var)) do something ...
}
}
$some_external_var =true;
$obj = new myclass();
$obj->myfunction();
Thanks
You'll need to use the global keyword inside your function, to make your external variable visible to that function.
For instance :
$my_var_2 = 'glop';
function test_2()
{
global $my_var_2;
var_dump($my_var_2); // string 'glop' (length=4)
}
test_2();
You could also use the $GLOBALS array, which is always visible, even inside functions.
But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !
A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...
Global $some_external_var;
function myfunction() {
Global $some_external_var;
if (!empty($some_external_var)) do something ...
}
}
But because Global automatically sets it, check if it isn't empty.
that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.
Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?
Use Setters and Getters or maybe a centralized config like:
function config()
{
static $data;
if(!isset($data))
{
$data = new stdClass();
}
return $data;
}
class myClass
{
public function myFunction()
{
echo "config()->myConfigVar: " . config()->myConfigVar;
}
}
and the use it:
config()->myConfigVar = "Hello world";
$myClass = new myClass();
$myClass->myFunction();
http://www.evanbot.com/article/universally-accessible-data-php/24

Categories