I want to make a global variable that can be used inside functions. But a few hours of experiments did not give me any results. What I want:

$qwe='knot'; function(){ echo $qwe; } 

At the same time, I do not want to use the global operator or access the variable through the superglobal array $GLOBALS , because I have a lot of functions in the code and each of them requires global variables, and it’s just not aesthetically pleasing and causes me to get riddled.

I tried to create a constant with ArrayObject inside to minimize the code and get the following syntax inside functions:

 define('q',new ArrayObject($_POST)); function(){ echo q->qwe; } 

Although the constant is available inside functions, you can only put a regular array in it, and, moreover, you cannot assign new properties to it. Therefore, it is impossible to work with this option.

I also saw the option to install an additional php extension to create my own superglobal variables in php.ini . Seen here . It would be a great option if you could do the same thing, but right in the code.

Is there any way today, even the most obscene, to create a global variable in PHP?

PS A static field in a class in no way resembles a variable and does not fit the question.

PSS Please do not need to convince me to rebuild the program architecture, I need an answer to this specific question, at least for cognitive reasons.

I can not help those who do not understand the question. How can I fix my post so that these people become smarter? I need a global variable - I am offered to write singltons or functions and wonder why I do not accept their answers. BUT I ABOUT CREATING A VARIABLE ASKED! My question does not sound like: "one hundred and one way to access the global variable from a function", but apparently for all it is exactly that. Actually, my question is very interesting and the solution that is really savvy is not enough for the whole PHP community.

And apparently any attempt at reasoning and discussion about the question asked leads to confusion and misunderstanding. Next time, I’ll just be minus and roughly otshivat everyone who offers off-topic options.

Closed due to the fact that it is necessary to reformulate the question so that it was possible to give an objectively correct answer by the participants Edward , Mark Shevchenko , AK , 0xdb , Kosta B. July 25, '18 at 12:14 .

The question gives rise to endless debates and discussions based not on knowledge, but on opinions. To get an answer, rephrase your question so that it can be given an unambiguously correct answer, or delete the question altogether. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    You will then be saved by the correct application architecture. - Manitikyl 4:08 pm
  • @Manitikyl I do not need to save. I need a way to create a global variable. Of that I am sure from mane to tail. - Diskyp pm
  • 2
    Мне нужен способ создать глобальную переменную - so use $GLOBALS . This is the best option, but you want crutches, well ... - Manitikyl
  • 2
    Do not want GLOBALS? Create a MyGlobals singleton and get MyGlobals :: get ('myGlobalVariable'); - Dmitry Kozlov
  • 2
    @Diskyp you need to change the programming language, I have published all the options, for those who understand what he wants, you want magic, it's the other way around. - Manitikyl 4:38 pm

4 answers 4

Option 1:

http://php.net/manual/ru/reserved.variables.globals.php

 function test(){ echo $GLOBALS['qwe']; } $GLOBALS['qwe'] = 'knot'; test(); 

Option 2

 class GlobalClass { static $_stack = array(); static function get($key) { return (isset(self::$_stack[$key])) ? self::$_stack[$key] : NULL; } static function add($key, $value = NULL) { self::$_stack[$key] = $value; } } function test(){ echo GlobalClass::get('key1'); } GlobalClass::add('key1', 'value1'); test(); 

Option 3:

 class GlobalClass { public $_stack = array(); function get($key) { return (isset($this->_stack[$key])) ? $this->_stack[$key] : NULL; } function add($key, $value = NULL) { $this->_stack[$key] = $value; } } class NowClass extends GlobalClass { function __construct() { $this->add('key1', 'value1'); } function test() { echo $this->get('key1'); } } $class = new NowClass; $class->test(); 

Option 4:

 $global_stack = array(); function global_get($key) { global $global_stack; return (isset($global_stack[$key])) ? $global_stack[$key] : NULL; } function global_add($key, $value = NULL) { global $global_stack; $global_stack[$key] = $value; } class NowClass { function __construct() { global_add('key1', 'value1'); } function test() { echo global_get('key1'); } } $class = new NowClass; $class->test(); 
  • Can you provide a working example? I did not see the answer there satisfying my question. - Diskyp 4:05 pm
  • I quote myself: At the same time, I do not want to use the global operator or access the variable via the superglobal array $GLOBALS - Diskyp 4:06 pm
  • These methods create functions, as you can see from the question, I'm trying to create a variable. - Diskyp
  • @Diskyp what do you want? do you imagine? You want to create $a = 5; in one place $a = 5; and then $a output anywhere wherever it pleases? It does not work. According to your questions it is clear that you do not mind using echo q->qwe; if you need only one bug, then make a class of one bug. - Manitikyl pm
  • Everything is not right, and I stopped at my own compiler of an additional symbol for global variables. However, the truth has not yet been found. - Diskyp
 /** * @property int $id */ class V { /** * @var V $ar */ public static $ar = []; private static $data = []; public function __get($name){ return self::$data[$name]; } public function __set($name, $value){ self::$data[$name] = $value; } public function getAll(){ return self::$data; } /** * @return $this; */ public static function init(){ if(!self::$ar){ self::$ar = new self(); } return self::$ar; } } //Прежде чем использовать нужно инициализация класса V::init(); V::$ar->id = 1; print_r(V::$ar->getAll()); 
  • Thanks for the detailed answer, I can agree that this is the best cancer on this bezrybe, but still it makes writing twice as many meaningless code than if there was an opportunity to simply create a global variable. I need some kind of sophisticated and revolutionary solution, maybe with a change in php.ini on the fly or something else. My experiments are still going on - Diskyp
  • In the case of autocompletion by the IDE and the provision of possible options, the code can and does not get much longer, but writing it is faster and easier to debug. You try it, you will like it) And in the name of a global variable it is possible and wrong, and in the case of a non-standard syntax there is no highlighting and validation. I would be crazy if I had a code like this dl4.joxi.net/drive/2018/07/24/0012/2001/813009/09/… - Ninazu
  • Heh, I really have no problems with validation, because it simply does not exist. I'm too lazy even to create a fake connection to the servers to activate the webshit license. In my sublim, there is no difference at all, and the ~ sign ~ recognized as the operator prntscr.com/ka8hef . And to give a really killer argument, I'm a fan of hardcore and CSS syntax and work with the js framework, which translates almost all client code into an Emmet-like syntax. I do not exactly scare me with additional lines. - Diskyp
  • @Diskyp Well, it's good that you write the code yourself, but God forbid some poor thing to support your code while you are tanning in the Seychelles. Updated the answer (if you have already decided to save letters) - Ninazu
  • Well, no, in my empire of perfect syntax, I allow only the elect, and they can rightfully consider themselves lucky. In my worldview, let the whole world read my docks and manuals rather than spend my life on someone else’s, which I don’t like. - Diskyp
 $tr = $_Post['responce']; $GLOBALS['a'] = $tr; 
  • In general, does not relate to the topic of the question, the author is at least an inattentive person. - Diskyp

In the absence of a better option, I decided to create my own small compiler of an additional symbol for variables:

 eval(preg_replace('/~\$([\w\d]+)/','$GLOBALS["$1"]',' ~$globalVar="WoW!"; function qwe(){ echo ~$globalVar; } qwe(); ')); 

Only instead of the string in eval - file_get_contents on the file called by the php client.

My syntax do not touch! This is my style and I want all the code behind my authorship to look like this.

  • 2
    If you need a global variable, can you use static class properties? IMHO, this option is much more literate than using an associative array, it is closer to the PLO and teaches a good programming style, like java - Alexander
  • @ Alexander I have been familiar with OOP for a long time already, I even wrote my full-fledged framework, though I’ve written js to create a SPA attachment. Last year I do not study, but I pervert to make my code as comfortable and aesthetic as possible. Therefore, I need exactly what I need. - Diskyp pm
  • one
    eval ... Well, if you do not care about the loss of productivity in half and potentially vulnerable team, then why not? - Alexander
  • 2
    But what if the code doesn’t exactly meet the same combination of characters inside text strings or in the form of an included html code and you will never use bitwise NOT (the operator ~ ) in your life, that solution is nothing. Especially if you make an assembly system that does this replacement not every time you run the file, but in the application development cycle, automatically create final .php based on the source code. Or at worst for this purpose try using auto_prepend_file. Although if you are hampered by the framework of such a boring php, can change the language - Mike
  • By the way, @Mike did not know at all that this symbol was an operator, thanks for an extra couple of bits of useful information in my brain. With strings, of course, you can get obosrams, I thought about it, but I made this system for the server API, where there are almost no rows, except for exapsons. But enivey is just a crutch for now and I don’t even deny it. I really wanted to go to the node, but I’m too lazy to study its features, just to write one API for my js framework. Because I decided to squeeze everything out. - Diskyp