Roberts R Posted July 29, 2020 Share Posted July 29, 2020 Hello. I'm having little trouble with setup. Having global variable in _init.php and not being able to access it? $test = "test"; function text() { global $test; return $test; } and using this function in templates returns null. What i have to do is create function that I use in templates. This function does some checks based on global value and returns string. Maybe there are other way to implement it? Link to comment Share on other sites More sharing options...
MoritzLost Posted July 29, 2020 Share Posted July 29, 2020 You $test variable may have been overwritten somewhere. In general, global variables are considered bad style because of their lack of scoping. For things you need to access from multiple places, I would either use the $config object or the setting() function: $config->myCutomSetting = 'test'; setting('my-custom-setting', 'test'); // use from anywhere, even within functions echo wire('config')->myCustomSetting; // 'test' echo setting('my-custom-setting'); // 'test' Note that the setting() function requires $config->useFunctionsAPI = true 6 Link to comment Share on other sites More sharing options...
Roberts R Posted July 29, 2020 Author Share Posted July 29, 2020 3 hours ago, MoritzLost said: You $test variable may have be overwritten somewhere Its not or I'm not aware of how that would happen for tests I did before posting. 3 hours ago, MoritzLost said: bad style because of their lack of scoping. I'm always up for learning 3 hours ago, MoritzLost said: $config->myCutomSetting = 'test'; Does the trick. It seems that defining variables this way should be done in config.php file. Either way thanks for help. ? 1 Link to comment Share on other sites More sharing options...
kixe Posted July 29, 2020 Share Posted July 29, 2020 Do not use global unless you really know what you are doing. Read this: https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and $this->wire() is another option to assign global vars, especially for more complex stuff ... like class instances. /** * Get an API variable, create an API variable, or inject dependencies. * * * @param string|object $name Name of API variable to retrieve, set, or omit to retrieve the master ProcessWire object. * @param null|mixed $value Value to set if using this as a setter, otherwise omit. * @param bool $lock When using as a setter, specify true if you want to lock the value from future changes (default=false). * @return object|string|mixed * @throws WireException * * */ public function wire($name = '', $value = null, $lock = false) {} 4 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now