Answer the question
In order to leave comments, you need to log in
Where to store global variables?
Where, from the point of view of competent architecture, to store global variables?
For the sake of greater clarity of the question, I will describe the rest of the conditions of the problem, although many would probably mean them by default. Other conditions are:
* OOP;
* First of all, we are interested in the specifics of web applications built according to the MVC architecture.
PHP code example:
class Registry<br>
{<br>
private static $_data = array();<br><br>
/**<br>
* Установить переменную<br>
* @return true/false<br>
*/<br>
public static function set($key, $value)<br>
{<br>
if(array_key_exists($key,self::$_data)){<br>
return false;<br>
}<br>
self::$_data[$key] = $value;<br>
return true;<br>
}<br><br>
/**<br>
* Получить переменную<br>
* @return value/null<br>
*/<br>
public static function get($key)<br>
{<br>
if( !array_key_exists($key, self::$_data) ){<br>
return null;<br>
}<br>
return self::$_data[$key];<br>
}<br><br>
/**<br>
* Удалить переменную<br>
*/<br>
public static function delete($key)<br>
{<br>
unset(self::$_data[$key]);<br>
}<br>
}
Answer the question
In order to leave comments, you need to log in
“Maybe you can do without global variables at all?” This is a question you need to ask yourself personally.
And so, you have a main model that stores some property. In turn, each view and the main controller have a link to this model, and thus have access to the desired property of the model.
My inner voice tells me that the presence of global variables means that the application architecture is not well thought out. Those. each variable has its own meaning and must belong to the class to which the meaning of this variable belongs.
Global variables are not needed. If you need object instances, use the Singleton pattern. And in all other cases, most likely just the wrong architecture.
Can you give an example when you really may need global variables within an application?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question