Jump to content

using global variables in _init.php


Roberts R
 Share

Recommended Posts

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

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

  • Like 6
Link to comment
Share on other sites

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. ?

 

  • Like 1
Link to comment
Share on other sites

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) {}

 

  • Like 4
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...