PHP set global variable as handle for class - php

For some reason, when defining:
function __construct() {
if(!isset($_GLOBALS["className"])) {
$_GLOBALS["className"] = new className;
}
return true;
}
$_GLOBALS["className"]->classMethod();
PHP for some reason states that $_GLOBALS["className"] is undefined.
Oh, and the same also occurs even if I set the global value to something else, from within that class. I can test the value of the global through the construct or some other method, but not outside - it seems that the global is lost outside the class for some reason.
Is there a way to retain the global after declaring it from within an external class?
Any help is sincerely appreciated!

You want to use $GLOBALS and not $_GLOBALS:
http://php.net/manual/en/reserved.variables.globals.php
$_GLOBALS will just be available in your function scope.

Related

Specifying a global variable outside of function

I have a pretty long extensive function, and the only thing that would change for me to use it elsewhere in the application would be to change the global variable declared inside of it.
function some_function() {
global $sys;
// ... Do stuff
}
some_function();
I need to change global $sys; to global $lang; or possibly a few other things, but everything else would stay the same. I was thinking something like:
function some_function($global_var) {
global $global_var;
// ... Do stuff
}
some_function($sys);
... or maybe ...
some_function($lang);
How can this be done?
Instead of using global, you could just pass the "global var" as a parameter to the function by reference:
function some_function(&$global_var) {
// ... Do stuff
}
Then you could use this function elsewhere without requiring to change the "global var" name.
Also consider the use keyword to import a variable from outside the scope instead of working in the global scope.

Defining a global variable, and including functions that require it?

I have six functions that require a global variable. In an attempt to reduce redundancy, I wrote a new function that is triggered rather than triggering all six. This one function has a global $var that is required by the other functions.
So, it looks like this
function one_function_for_the_rest() {
global $importantVar;
functionOne();
functionTwo();
functionThree();
}
but the global variable is not being seen by the called functions. Am I doing this incorrectly, or is this a limitation I was not aware of?
You're not doing it correctly as the variable is defined when on_function_for... is called. An easier way for this would be just to have $importantVar; at the start of the code.
Or wrap your functions inside a class and put the variable inside the class.
e: so basically do : function myFunc($important) { stuff } and when calling the function do myFunc($importantVar)
example :
$asd = "lol";
class myclass {
public function lol($asd) {
echo $asd;
}
}
$obj = new myclass;
$obj->lol($asd);
You're not doing it correctly. Each function either needs to use the global scope identifier, like global $importantVar;, or have $importantVar passed as a parameter. Otherwise, the other functions don't have $importantVar in their respective scopes.
Simply calling a function from within one_function_for_the_rest does not tell that other function anything about global variables or variables used in one_function_for_the_rest. In technical terms, your function calls do not bring $importantVar into the respective scopes of functionOne, functionTwo, or functionThree.
PHP does not have the same scoping rules as most other languages have. That is the downside to not having to declare variables with var as in JavaScript or other similar constructs.
Basically in PHP, every function used is only available in that function. There are three exceptions:
The global keyword
The $this variable inside objects. This one is also "magic" as it's also available inside anonymous functions defined inside a class.
When declaring an anonymous functions you can bind variables to it using use.

require_once to global scope within a function

It seems that if require_once is called within function, the included file doesn't extend the global variable scope. How to require_once a file to global scope from within a function?
What I'm trying to do is some dynamic module loader:
function projects_init()
{
...
foreach ($projects as $p) {
require_once($p['PHPFile']);
$init_func = $p['init'];
if ($init_func)
$init_func();
}
}
If it is not possible to use require_once that way, what is the simplest solution for this? (Please no heavy frameworks.)
EDIT: it should also work for PHP 5.2.
To summarize all the information:
functions are not an issue, they will be global anyway this way
for global variables, there are 2 options:
declare them as global in the included file
declare them as global in that function (projects_init() in my case)
The above answer is right, you can use global to get what you need.
In the included file just declare the variables global at the beginning of the file, this way the code will run in the function scope but it will change the global variables(yes, you have to be careful and declare everything you need to change as global but it should work), example:
function a() {
require_once("a.php");
}
a();
echo $globalVariable;
and in the a.php file:
global $globalVariable;
$globalVariable="text";
Functions are not an issue (ref):
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
About global variables: As in an existing question regarding the scope of require and the like, the scope is defined where the use is. If you need something else, there are numerous answers (my take) that show how to deal with global variables, most making use of get_defined_vars.
You can use global to put a variable in the global scope.
http://php.net/manual/en/language.variables.scope.php

Forbid specific variable access from global scope

Is there a way to forbid a variable from being picked out of global scope?
Something like:
#index.php
$forbidden = 'you should not be able to access me outside this scope'; // maybe invoke a function or namespaces?
require 'stuff.php';
echo new stuff();
#stuff.php
class stuff
{
public function __toString()
{
global $forbidden; // to result in an error or something?
/*
just a random example, but yes, any way
to somehow make a variable not global?
*/
return 'I am forbidden';
}
}
Have no idea if it's possible, but anyways, interested in OOP only fashion.
Reason?
To disallow a specific class from being instantiated into a variable and then taken out from global scope to reuse it's functions. Make class completely "private", kind of like a master class that does all the automation.
Hope I've made myself clear.
The only way I can think of would be to "fake" global scope...
//index.php
function scope() {
require 'actual.php';
}
scope();
and now, putting code in actual.php looks like "normal" code but it actually is inside function scope. Obviously you can't declare functions or classes in actual.php now, but otherwise it behaves the same, with the exception that any variables declared will be in the function's scope instead of global scope.
I really wouldn't do this though. A beating with a stick usually works if someone does something stupid like globals like that ;)

global variables in php not working as expected

I'm having trouble with global variables in php. I have a $screen var set in one file, which requires another file that calls an initSession() defined in yet another file. The initSession() declares global $screen and then processes $screen further down using the value set in the very first script.
How is this possible?
To make things more confusing, if you try to set $screen again then call the initSession(), it uses the value first used once again. The following code will describe the process. Could someone have a go at explaining this?
$screen = "list1.inc"; // From model.php
require "controller.php"; // From model.php
initSession(); // From controller.php
global $screen; // From Include.Session.inc
echo $screen; // prints "list1.inc" // From anywhere
$screen = "delete1.inc"; // From model2.php
require "controller2.php"
initSession();
global $screen;
echo $screen; // prints "list1.inc"
Update:
If I declare $screen global again just before requiring the second model, $screen is updated properly for the initSession() method. Strange.
Global DOES NOT make the variable global. I know it's tricky :-)
Global says that a local variable will be used as if it was a variable with a higher scope.
E.G :
<?php
$var = "test"; // this is accessible in all the rest of the code, even an included one
function foo2()
{
global $var;
echo $var; // this print "test"
$var = 'test2';
}
global $var; // this is totally useless, unless this file is included inside a class or function
function foo()
{
echo $var; // this print nothing, you are using a local var
$var = 'test3';
}
foo();
foo2();
echo $var; // this will print 'test2'
?>
Note that global vars are rarely a good idea. You can code 99.99999% of the time without them and your code is much easier to maintain if you don't have fuzzy scopes. Avoid global if you can.
global $foo doesn't mean "make this variable global, so that everyone can use it". global $foo means "within the scope of this function, use the global variable $foo".
I am assuming from your example that each time, you are referring to $screen from within a function. If so you will need to use global $screen in each function.
You need to put "global $screen" in every function that references it, not just at the top of each file.
If you have a lot of variables you want to access during a task which uses many functions, consider making a 'context' object to hold the stuff:
//We're doing "foo", and we need importantString and relevantObject to do it
$fooContext = new StdClass(); //StdClass is an empty class
$fooContext->importantString = "a very important string";
$fooContext->relevantObject = new RelevantObject();
doFoo($fooContext);
Now just pass this object as a parameter to all the functions. You won't need global variables, and your function signatures stay clean. It's also easy to later replace the empty StdClass with a class that actually has relevant methods in it.
You must declare a variable as global before define values for it.
The global scope spans included and required files, you don't need to use the global keyword unless using the variable from within a function. You could try using the $GLOBALS array instead.
It is useless till it is in the function or a class. Global means that you can use a variable in any part of program. So if the global is not contained in the function or a class there is no use of using Global

Categories