I suppose this is a specific question, but for some reason, when I create a Thread like this:
require_once(__DIR__.'/myotherfile.php');
class StreamBufferInput extends Thread {
public function run(){
global $max_buffer_size;
global $data_source;
echo "DATA:" . $max_buffer_size;
...
}
}
myotherfile.php has those two variables declared in it (and they can be accessed from other classes, but my echo statement here prints DATA: and nothing else. I couldn't find much on doing global variables within classes, but I have a global declaration like this in a function of one of my other classes, and it works fine.
EDIT: Here is how I'm starting the Thread.
$stream = new StreamBufferInput();
$stream->start();
This is not possible in PHP at the moment. You cannot access global scope variables defined outside a thread from within the thread itself. However, you can execute a callable from within the thread, in the global scope by using Thread::globally, I believe this could help you achieve what you want.
You can read some more about this here
Related
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.
update:
the code i put below will be invoked by a form on other webpage. so that's why I didn't made a instance of a obj.
More detail code:
$serverloc='serverURL';
class Aclass{
function push(){
global $serverloc;
echo $serverloc;
funNotinClass();
}
function otherFunction(){
echo $serverloc;
}
}
funNotinClass(){
echo $serverloc;
}
There is a Class contains 2 functiona "push()" and "otherFunction()" and there is independent function "funNotinClass()" and push() calls it. The class is for a web form in other page. When user click submit the form call the class and use the push() function. A weird thing I found is that the global var $serverloc is invisible to push() and funNotinClass()(they don't print out any thing), but otherFuction() which is a function just like puch() inside of the Aclass can just use the $serverloc(I dont even add global in front of it). How strange....anyone know what is the reason caused this?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I read many information about the scope of a global var in php.
they all say a global var is defined outside of function or class and you can use it by using global this key word.
So this is my code
$serverloc='serverURL';
class Aclass{
function Afunction(){
global $serverloc;
echo $serverloc;
}
}
but when I run this class it didn't print anything out.
Is that because I did something wrong or global var just doesn't work this way. Since all the example I read before are just access a global var in functions directly not a function in a class
As per DaveRandom's comment - you haven't actually made an instance of an Aclass object.
This works and displays data as expected:
<?php
$serverloc='serverURL';
class Aclass{
global $serverloc;
function Afunction()
{
echo $serverloc;
}
}
$me = new Aclass();
$me->Afunction(); // output: serverURL
?>
Edit: DaveRandom seems to post asnwers as comments. Go Vote up some of his other answers, the rep belongs to him not me. I am his ghostwriter tonight.
If it is class globals you are after you could do like
class myClass
{
private $globVar = "myvariable";
function myClass()
{
return $this->globVar;
}
}
but when I run this class it didn't print anything out
You don't run classes, in the sense of executing them. A class is a just a data structure that holds data and functions related (called methods).
As most traditional data structures, you create instances of them (called objects), and then you execute actions on them. One way to execute actions on objects (instances of classes), is to pass a message for it to do something: that is calling a method.
So, in your case you could do:
$obj = new Aclass(); // create an object, instance of Aclass
$obj->Afunction(); // ask it to perform an action (call a method)
Having said that, sometimes you want to create a class only for grouping related functions, that never actually really share data within an object. Often they may share data through a global variable (eg.: $_SERVER, $_GET, etc). That may be the case of your design right there.
Such classes can have its methods executed without never instantiating them, like this:
Aclass::Afunction();
While relying on global variables is usually an indicator of quick'n dirty design, there are cases in which it really is the best trade-off. I'd say that a $serverlocation or $baseurl may very well be one of these cases. :)
See more:
The basics on classes and objects in the PHP manual
About the static keyword
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
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 ;)
inside of a function i have a $connection var what obviously stores my connection to mysql,
how can i call that var from inside other functions to save me having to paste the $connection var inside of every function that requires this var?
i have tried global to no avail.
many thanks
You could use the old global keyword.
function a() {
global $connection;
}
Or you could throw it in $GLOBALS (this will help you get it out of the function defined it in).
Neither of them are too pretty.
Or you could pass in the $connection as an argument.
The most common way of dealing with a database connection is to have its creation handled by a singleton pattern, or have a base class with OO that has a $this->db available, that all your other classes can inherit from.
Pass the connection as a parameter to the functions that need it. It keeps your code clean and re-usable.
Another solution would be to use a class and make the connection a class variable. You will just use $this->connection every time you need this, but this is not really a solution if you already have a lot of code written in a lot of files.
Declare the variable outside the function, then make it accessible inside each function you need it by using the global keyword.
$globalName = "Zoe";
function sayHello() {
$localName = "Harry";
echo "Hello, $localName!";
global $globalName;
echo "Hello, $globalName!";
}
sayHello();
stolen from http://www.elated.com/articles/php-variable-scope-all-you-need-to-know/