make a variable inside a function accessible to other functions? - php

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/

Related

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.

call PHP PDO wrapper class from another class

I'm planning to use a PHP PDO wrapper class from here: http://www.imavex.com/php-pdo-wrapper-class/
I initialized the class with:
$db = new db("mysql:host=$sitedbHost;port=3306;dbname=$sitedbName", "$sitedbUser", "$sitedbPass");
The problem is, that I don't like the idea to make global $db on every function on my other classes like this:
class User
{
function getUserDomains($user_id)
{
global $db;
return $db->select("domains");
}
}
Any help will be highly appreciated.
If you class requires it in order to work, you can inject it in the constructor:
class User {
public function __construct(Database $db) {
$this->db = $db;
}
}
You can then access the database object from $this->db. (Note, I assumed $db is an instance of the Database class. Change it as appropriate).
Here is something for you:
Check new PDO Class Wrapper on GitHub
I don't like the idea to make global $db on every function on my other classes
Well, make it global in constructor only (or pass it as a parameter), and then use as a class variable,
return $this->db->select("domains");
Honestly, you can't avoid passing $db to the function somehow. There is no magic. Whatever fashionable way you choose, you'll end up with setting your $db variable this way or another, no matter how it's called, "dependence injection", "global" or "use the Force, Luke".
I'd vote for global as it's plain and simple.
By the way, this framework is inflexible and insecure. Better use safeMysql as it's way more secure and flexible

Scoping issue with global when called from included file included within a function?

I have a file, standalone.php, that's meant to be run as its own script, directly from the browser. It defines functions, classes and includes other files. It works fine when directly invoked.
It has code in it like this:
$DB = new Database(DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_SERVER, '', true);
function DB() { global $DB; return $DB; }
When run alone, $DB is defined in the global name space, and the function that returns the object grabs the global $DB object. Again, this works.
The problem is, i have another file, sometimesInvoker.php, that is called from the browser, and in some cases, needs to include standalone.php and output to the browser as if standalone.php had been invoked directly. It cannot use a redirect, and it cannot include standalone.php via URL.
The code in sometimesInvoker.php is:
LoadPage();
function LoadPage(){
include standalone.php;
}
So the hierarchy looks like:
Global name space / sometimesInvoker.php
LoadPage() function
standalone.php - thinks its global but it isn't
$DB - declared intending to be global but is actually a variable inside LoadPage() function?
function DB() - calls global DB and looks inside sometimesInvoker.php for a $DB var which isn't there, should be going up one level to LoadPage() function and grabbing that var.
So I get the problem, but how to solve it? I need a way for a function to get a variable that is one level above it, regardless of if the next level up is global or not. Any ideas?
In sometimesInvoker.php make the very first line require_once 'standalone.php';
I need a way for a function to get a variable that is one level above it, regardless of if the next level up is global or not.
I don't know if i understand you correctly but, there are a few ways of making variables available in sub functions;
Use "global" to use variables in another scope:
$db='whatever';
function XXYYY(){
global $db;
echo $db;
}
Or pass the variables into the function:
$db='whatever';
function XXYYY($db){
echo $db;
}
Or am i missing the point?
This is a workaround I'm using to solve the problem for now. Change the DB() function to:
function DB() {
static $DB = null;
if(is_null($DB))
$DB = new Database(DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_SERVER, '', true);
return $DB;
}
Using a static variable in the DB function let's me instantiate the class once instead of relying on a global var. This solves the problem in this case, but I'd still be interested to know if you can access a var outside of a function if that var is in a parent function, not the global namespace?

Mysqli conn include file - global variable PHP

I'm including the MySQLi connection file in the constructor of a PHP class. Since I need to reach the connect variable in methods in this class I need to make the variable global. I always heard global variables are bad. So I wonder, is this the only/best way to deal with this?
class CheckUser {
function __construct() {
require_once('mysqli.php');
}
function checkEmail($email) {
// sql code here
}
}
That's just a meme. (And dependency injection is coming right up...)
Your connection handle is a central resource. Use it as such. A global variable is perfectly fine and the intended langauge construct for that. It makes sense as long as you only have one database / connection.
If global variables were bad, we wouldn't have $_GET and $_POST (which are actual global variables).
Should your class (guessing here) be the central access point to database queries, then keeing the handle as simple property is just as cromulent.
function __construct() {
require_once('mysqli.php');
$this->db = $db;
}
Or whatever local variable the mysqli.php script created.

PHP Classes and global variables

I recently begun to use classes. I've been using procedural programming for quite a while so it has been a bit challenging.
My question.
If I have a class like this:
class Example {
public $name;
public $whatever;
public $yearAdded
public function __construct($name, $whatever=NULL, $dateAdded)
{
some trival code here;
}
}
How can I make $yearAdded use a global variable I set up somewhere else in another script?
FOR EXAMPLE:
global $currentYear = date('Y');
Would I have to do this way
new example($name, $whatever, $currentTime);
or is there a way to specify within the class to always use $currentYear for $yearAdded.
The global keyword doesn't work the way you think it does. It does not make a variable have global scope. All it does is specify to the function that you call it in that you want to use the variable in the outer scope.
For example:
$a="test";
function something() {
global $a;
echo $a; //Outputs: test
}
If you want to make a variable global so that it can be accessed from within a class, you need to use the $GLOBALS superglobal.
http://www.php.net/manual/en/reserved.variables.globals.php
This is not considered to be the best OOP way of doing things, but will get the job done.
You already have a builtin time() function, so why do you need a home-grown global variable in your constructor?
If you think carefully about how you are using globals, you'll find out that there are usually better ways of accessing the same info -- e.g. system environment variables, configuration files, etc.

Categories