How to "globalize" PHP variables? - php

I have a page named ChangeApprovalInfo.php - It has a function called Row_Rendered as follows;
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$RecordOwner = $this->RequestUser->CurrentValue;
echo $RecordOwner;
}
Echoing $RecordOwner gets me the data I will need for a sql query on another page....
I have another page called ChangeApprovalEdit.php - This page has
<?php include_once "ChangeApprovalinfo.php" ?>
at the top of the file.
ChangeApprovalEdit.php has a function where I need the $RecordOwner variable as defined in ChangedApprovalInfo.php
If I add "echo $RecordOwner" on the ChangeApprovalEdit.php page, I get an error saying it's an unknown variable. My understanding is that I need to "make it global" or some such business. I know very little about PHP and the pages I am editing are long and complex. (to me, at least)
What do I need to do? I know that the information I have provided might not be enough to answer the question. I don't know enough to even know exactly what I need to ask. If more information is needed, I will edit and follow up.
pastebin of the files
ChangeApprovalInfo.php = http://pastebin.com/bSRM1wwN
ChangeApprovalEdit.php = http://pastebin.com/AStG9pqb
EDIT:
Changing Row_Rendered to this seems to be more effective. I'm having trouble seeing WHERE I can later echo this variable... but I'm getting somewhere with this...
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$GLOBALS['RecordOwner'] = $this->RequestUser->CurrentValue;
}

Don't echo variables from functions, which just outputs them to the standard output. return them from the function so you can use the value elsewhere as well.
function Row_Rendered() {
$RecordOwner = $this->RequestUser->CurrentValue;
return $RecordOwner;
}
Then instead of
$obj->Row_Rendered();
use
echo $obj->Row_Rendered();
and if you want to use the value elsewhere, use
$value = $obj->Row_Rendered();

You can do a couple of things:
First, you can return $RecordOwner from the function, and store its value in a variable. This method is usually preferred.
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$RecordOwner = $this->RequestUser->CurrentValue;
echo $RecordOwner;
return $RecordOwner;
}
// Store it in a variable when calling the function.
$RecordOwner = Row_Rendered();
Or, you can make it global inside the function:
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$GLOBALS['RecordOwner'] = $this->RequestUser->CurrentValue;
echo $GLOBALS['RecordOwner'];
}

You can use the $GLOBALS superglobals array, like this:
function Row_Rendered() {
$GLOBALS['RecordOwner'] = $this->RequestUser->CurrentValue;
}
However, you should not do that. Instead, refactor your application so that the view in ChangeApprovalinfo.php just contains a function, which is then called with the appropriate parameters.

EDIT: Chaning Row_Rendered to this seems to be more effective. I'm having trouble seeing WHERE I can later echo this variable... but I'm getting somewhere with this...
function Row_Rendered() {
// To view properties of field class, use:
//var_dump($this-><FieldName>);
$GLOBALS['RecordOwner'] = $this->RequestUser->CurrentValue;
}
I feel compelled to write another answer to this update. Let me demonstrate the use of globals as seen from outside that function:
$obj->Row_Rendered();
$obj->foobar();
echo $GLOBALS['RecordOwner'];
Quick, what will be echoed and where does that value come from? Well, it depends on what $obj-foobar() does. Maybe it changes the global variable. Maybe it doesn't. Who knows if the variable has been set at all? How would you trace back what happened exactly without adding a debug line after every single function call?
And that's just three lines of code. Imagine that in an application of any complexity.
Now, the same thing if I return the value from Row_Rendered:
$owner = $obj->Row_Rendered();
$obj->foobar();
echo $owner;
If the Row_Rendered method is behaving as it should (returning the owner), this code is very predictable. If you do not follow this pattern, you'll have a hell of a time getting anything done when the application grows to any halfway complex size.

Set the variable as global from within the function
$my_global_var = "old value";
function doing_stuff(){
global $my_global_var; //this will use the global variable instead of creating a local one
$my_global_var = "new value";
}
echo $my_global_var;//returns "new value"

Related

$_GLOBAL variables set in config file are not being read correctly

this might be a stupid question but I'm stuck here at this silly problem for the part 2 hours.
I have this function which checks if a particular config file's variable are not empty.
Here's the function :-
include 'inc.config.php';
function not_valid_settings()
{
if((empty($_GLOBAL['id'])) || (empty($_GLOBAL['username'])) || empty($_GLOBAL['password']))
{
return true;
}
else
{
return false;
}
}
Here's the config inc.config.php file:
$_GLOBAL=array();
$_GLOBAL['id'] = "asas";
$_GLOBAL['username'] = "asas";
$_GLOBAL['password'] = 'as';
Function Calling
include 'inc/inc.functions.php';
if(not_valid_settings())
{
echo "Please enter correct entries in inc/inc.config.php";
exit();
}
For some reason, I always get the Please enter correct details. Even if my $_GLOBAL['username']='';.
What wrong am I doing here?
The problem is that $_GLOBAL appears to be a PHP superglobal, but it is not -- there is no such superglobal in PHP. As a result, this variable is not immediately accessible everywhere. If you add global $_GLOBAL; as the first line if your function, your code should work:
function not_valid_settings()
{
global $_GLOBAL;
Perhaps you meant to use $GLOBALS instead, though I would strongly advise against it. Use a name like $SETTINGS instead, and don't forget to use global $SETTINGS; in functions where you need to access the settings object.
In general, you should avoid choosing variable names that start with $_ unless they are PHP superglobals; this prefix implies a superglobal, while your variable is not. This will create unnecessary confusion.
$GLOBALS is what you mean to use, though this is not a good practice.
http://php.net/manual/en/reserved.variables.globals.php

Using php pointers on function?

I'm creating a website and somewhere in the code I need to query for a user attribute (ex:account state) and in the same row I have the reason, case is account state is "suspended".
I'm trying to minimize the requests to the database, so I created a function to verify account state.
function getAccountState($userid,$reason){}
What I am trying to do is if account state is "suspended" I would change the $reason to "the database reason".
I've already done that but if I change the $reason inside the function, outside the function it will not change.
I searched for "php pointers" on google but I think there is not such thing.
Is there a way to do this? Other way I'll just make another database request...
You could of course pass the variable by reference but as you don't seem to need it, I would just return it from the function:
function getAccountState($userid){
// your code
return $reason;
}
and call it like:
$reason = getAccountState($userid);
If you want to stay your code as it is now, you could pass the variable by reference:
function getAccountState($userid,&$reason){}
^ like so
You could consider passing it in by reference. Or perhaps just changing the function to return the correct information.
In the definition of functions you can tell that $reason argument is passed by reference, not value. To do so, use & in front of variable:
function getAccountState($userid,& $reason){}
You are looking for references, in PHP terminology, not pointers.
They work this way :
function getAccountState($userid, &$reason){ // Notice the &
$reason = "database locked"; // Use it as a regular variable
}
getAccountState(12345, $reason); // Here, it is written as a regular variable, but it is a ref.
echo $reason; // echoes "database locked"

How to pass additional parameter to wordpress filter?

add_filter('wp_list_pages_excludes', 'gr_wp_list_pages_excludes');
function gr_wp_list_pages_excludes($exclude_array) {
$id_array=$array('22');
$exclude_array=array_merge($id_array, $exclude_array);
return $exclude_array;
}
I'm a newbie to wordpress. The above code works fine. But I need to pass additional argument, say $mu_cust_arg to the function gr_wp_list_pages_excludes. How can I make use of it via apply_filters, or any other methods?
Any help is appreciated.
Thanks in advance.
You can indeed add multiple arguments to a filter/action, you just need to tell WordPress how many arguments to expect
Example, which won't work:
add_filter('some_filter', function($argument_one, $argument_two) {
// won't work
});
apply_filters('some_filter', 'foo', 'bar'); // won't work
It will fail with an error that too many arguments was provided.
Instead, you need to add this:
add_filter('some_filter', function($argument_one, $argument_two) {
// works!
$arugment_one; // foo
$arugment_two; // bar
}, 10, 2); // 2 == amount of arguments expected
apply_filters('some_filter', 'foo', 'bar');
Because WP doesn't accept closures as callbacks (at least, certainly not for add_filter()) the short answer is "you can't". At least, not in a tidy way.
There are a couple of options here, depending on what you are doing. The first is the best, but you may not be able to use it:
Write a wrapper function that calls your function:
function gr_wp_list_pages_excludes_1 ($exclude_array) {
$custom_arg = 'whatever';
gr_wp_list_pages_excludes_1($exclude_array, $custom_arg)
}
This will only work if you are always passing the same custom argument in a given situation - you would write one of these wrapper functions for each different situation, and pass the name of the wrapper function to add_filter(). Alternatively, if you want it to be truly dynamic, you would need to...
Use a global variable: (Ref: Variable scope, $GLOBALS)
function gr_wp_list_pages_excludes($exclude_array) {
global $gr_wp_list_pages_excludes_custom_arg;
$id_array=$array('22');
$exclude_array=array_merge($id_array, $exclude_array);
return $exclude_array;
}
Using this approach means that you can pass any data you like into the function by assigning it to $gr_wp_list_pages_excludes_custom_arg in the global scope. This is generally regarded as bad practice and heavily frowned upon, because it makes for messy and unreadable code and leaves the memory space littered with extra variables. Note that I have made the variable name very long and specific to the function to avoid collisions - another problem with using global variables. While this will work, only use it if you absolutely have to.
Very simple!
add_filter('filter_name','my_func',10,3); //three parameters lets say..
my_func($first,$second,$third){
//............
}
then
echo apply_filters('filter_name',$a,$b,$c);

PHP Variable not passing to function

I have the following setup:
class.staff.php
This defines many variables, the one I'm working with right now is $thisuser->getStaffLang();
class.language.php
(Only a function, not a class) This file runs a sql query based on the one variable I pass it from header.inc.php as well as it should pull the staff members unique language ID.
The function is:
function translate($TRANSLATION){
$sql="SELECT $TRANSLATION FROM ".LANGUAGE_TABLE." WHERE LANGUAGE_ID=".$thisuser->getStaffLang;
$query = mysql_query($sql);
$translation = mysql_result($query,0);
print $translation;
}
header.inc.php
First file I'm working with using this function
example translation entry is:
translate('TEXT_WELCOME_BACK_STAFF');
My problem is that when I'm outside the function $thisuser->getStaffLang; is populated but inside the function it is empty. I really don't want to have to pass the same variable to the function over and over as some files can have upwards of 20 translations in them and that seems like alot of redundant coding. Can someone tell me how in the heck I can get that variable to be recognized by the function without have to pass it to it every single time when calling the function? Hope this wasn't clear as mud. :\
Note: Both class.language.php (where the function is and doesn't work) and header.inc.php (where the variable alone works) have required class.staff.php. So they both should be able to utilize that code/variable.
add global $thisuser; at the beggining of translate()
You need to mark $thisuser as global. See below:
function translate($TRANSLATION)
{
global $thisuser; //<---- MUST MARK global
$sql="SELECT $TRANSLATION FROM ".LANGUAGE_TABLE." WHERE LANGUAGE_ID=".$thisuser->getStaffLang;
$query = mysql_query($sql);
$translation = mysql_result($query,0);
print $translation;
}
$thisuser->getStaffLang is probably not a global. You should either make it global, by adding global $thisuser to the first line of the function,
or better, pass this variable also in the function scope. So something like this:
function translate($TRANSLATION, $stafflang){
// function here
}
translate('TEXT_WELCOME_BACK_STAFF',$thisuser->getStaffLang);

Drupal - How can I make an array globally accessible?

I'm using this code in a views field template (in this case views-view-field--all-members--uid.tpl.php):
<?php
$users_friends = flag_friend_get_friends($user->uid);
$users_friends_ids = array();
foreach ($users_friends as $id => $value) {
$users_friends_ids[] = $id;
}
?>
It basically gets the user ids of friends and puts them in an array so I can check if the field matches any of the user ids.
So my problem is that I don't want to have this within this template (for a few reasons), but if I don't I can't access the array. How can I make this array globally accessible?
Without knowing your "few reasons", I can't say if this is the answer for sure. My own reasons would probably be that I don't want the same code executing a bunch of times, and I'd rather not have the same exact code in multiple places.
I would then create a function with a static variable to hold the friends array.
function mymodule_get_friends_ids() {
// pull in the current global user variable
global $user;
// call up the static variable
static $users_friends_ids;
// return if this static var has already been set
if (is_array($users_friends_ids)) {
return $users_friends_ids;
}
// if we hit here, then this function has not been
// run yet for this page load.
// init array
$users_friends_ids = array();
// if user is anon, no need to go on
if (user_is_anonymous()) {
return $users_friends_ids;
}
// get friends array
$users_friends = flag_friend_get_friends($user->uid);
// build ids array
foreach ($users_friends as $id => $value) {
$users_friends_ids[] = $id;
}
return $users_friends_ids;
}
Now in your templates, you can call mymodule_get_friends_ids() in as many places as you want, and the working code below the first return will only get executed the first time it is called.
Coder1's advice is very good - it keeps you from populating your global variable namespace with a lot of junk. It's probably the most "elegant." It might not be the easiest to use if you are rather new to PHP (which I'm guessing might be the case if it's hard to get your head around returning arrays, but that's ok).
However, if this is really a priority, you probably don't care about having one extra global variable.
I suppose I may be stating the obvious here - but you can, at pretty much any point in execution (provided the information you need has already been generated - e.g., the $user variable has been populated), do this:
$GLOBALS['users_friends_ids'] = /* your code goes here */
Then in your template, you access this by ...
$friendsArray = $GLOBALS['users_friends_ids'];
Or you can simply use the construct
global $user_friends_ids;
when you want to initialize the variable, or access it inside a function or class (which is the case for your template files - they are called inside functions, so you need to globalize or use the $GLOBALS array, which is "automagically" all of the variables active in the global namespace).
The most "logical" place to do this would be inside a module using one of the many hooks available, to execute this code only once. hook_init() might do it for you, if the user object is already loaded at this point (not sure, you'll have to test). But you might not want to figure out making Drupal modules (it's not that difficult).
If you are doing this inside a template (and though it's not good practice, many Drupal site owners with a beginning knowledge of PHP put everything in templates), you'll want to know which template code is being executed when. Node template code tends to be executed before page template code - which is logical, since otherwise the variables for node content in the page template wouldn't be populated.
If you have listings of nodes, they'll be calling this code multiple times, so you'll end up doing something similar to what Coder1 is describing. If you don't want to create your own small module, you could put the function declaration he's written in your theme's template.php file, since it's called only once. You don't want to put function declarations in the tpl.php files, since they are sometimes called more than once (and you aren't allowed to declare functions more than once).
If you have a hard time understanding the function and the return, you can always do something like this in your code (which is very, very inelegant - but it's better to have inelegant code that you do understand, than elegant code that's you don't).
if(!isset($GLOBALS['users_friends_ids'])) {
$GLOBALS['users_friends_ids'] = /* your code here */
}

Categories