Changing User-Defined Global Variable Value in ExpressionEngine - php

Say I've got a global variable which I'm accessing inside a PHP block, which compares to a querystring... if the comparison is true I want to set the value for a global EE variable so that all the other template pages can recognise that the value is not what it normally is - is this possible, or are the global user-defined variables constants?
Thanks,
Dan

$this->EE->config->_global_vars['foo'] = 'bar';
But keep in mind that the variable may have already been parsed before you have a chance to change it, depending on where and how it's used (see EE2's parse order discusssion).

You can use the PHP $GLOBAL Superglobal Array, for such cases. Say you have written a variable in any block of a particular page as $a = 123;.
Now in the same page, but in another block, you can easily change it to something else as $GLOBALS['a'] = 456;.
Hope it helps.

Related

Define/set PHP variable

I often get PHP errors about a variable not defined. I'm also wondering what is best practice for setting session variables. Currently I'm doing this:
session_start();
if (!isset($_SESSION["myVar"]))
$_SESSION["myVar"] = "";
But this seems untidy to me. I know there is a PHP unset function, but what is the equivalent to simply set/define a variable into existence, without setting an initial value?
Php has dynamic variable allocation and typing. When a variable is first referenced within a program, memory is allocated for its use.
Meaning that unless you don't assign a value, a variable can't be declared, like say, in java.
Best way how to make sure you "declare" all your variables?
Assign them to null or empty string at the beginning of each function / method.
About session variables, I'd apply the same logic.

Is it necessary to Initialize / Declare variable in PHP?

Is it necessary to initialize / declare a variable before a loop or a function?
Whether I initialize / declare variable before or not my code still works.
I'm sharing demo code for what I actually mean:
$cars = null;
foreach ($build as $brand) {
$cars .= $brand . ",";
}
echo $cars;
Or
foreach ($build as $brand) {
$cars .= $brand . ",";
}
echo $cars;
Both pieces of code works same for me, so is it necessary to initialize / declare a variable at the beginning?
PHP does not require it, but it is a good practice to always initialize your variables.
If you don't initialize your variables with a default value, the PHP engine will do a type cast depending on how you are using the variable. This sometimes will lead to unexpected behaviour.
So in short, in my opinion, always set a default value for your variables.
P.S.
In your case the value should be set to "" (empty string), instead of null, since you are using it to concatenate other strings.
Edit
As others (#n-dru) have noted, if you don't set a default value a notice will be generated.
You had better assign it an empty string $cars = '';, otherwise (in case you have error reporting on) you should see a notice:
Notice: Undefined variable: cars
PHP will assume it was empty and the resultant string will be the same, but you should prefer not to cause an extra overhead caused by a need of logging that Notice. So performance-wise it is better to assign it empty first.
Besides, using editors like Aptana, etc, you may wish to press F3 to see where given variable originated from. And it is so comfortable to have it initialized somewhere. So debugging-wise it is also better to have obvious place of the variable's birth.
It depends: If you declare a variable outside a function, it has a "global scope", that means it can only be accessed outside of a function.
If a variable is declared inside a function, it has a "local scope" and can be used only inside that function.
(http://www.w3schools.com/php/php_variables.asp)
But it seems that the variable "cars" that you defined outside the function works for your function even without the global keyword...

PHP, an odd variable scope?

This more a question about the why then 'how-to', yet it has been annoying me for some days now. Currently I am doing some work with CodeIgniter and going back to PHP temporarily from Ruby, bugs me about the following scoping magic.
<?php $query = $this->db->get('articles', 2);
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$data[] = $row; # <-- first appearance here
}
return $data; # <--- :S what?!
}
As you can see, I am not exactly a PHP guru, yet the idea of local scope bugs me that outside the foreach loop the variable is 'available'. So I tried this out inside a view:
<?php
if($a==1)
{
$b = 2;
}
echo $b;
?>
Which result in an error message:
Message: Undefined variable: b
The PHP manual tells about the local scoping, yet I am still wondering why this happens and if there are special rules I do not know about. And it scares me :)
Thanks for sharing ideas,
Only functions create a new local scope. Curly braces by themselves do not. Curly braces are just an auxillary construct for other language structures (if, while or foreach).
And whereever you access any variable in a local scope doesn't matter. The local scope is an implicit dictionary behind the scenes (see get_defined_vars). You might get a debug notice by accessing previously undefined variables, but that's about it.
In your specific example it seems, you are even just operating in the global scope.
foreach does not create any variable scope in PHP so it is natural if variable is available outside foreach
for the second question the $a is not equal to the 1 hence $b is not initialized and throw notice when you access outside. If you assign value 1 to $a and test it you will wonder the notices will gone.
Here is nothing like scope.
See: http://php.net/manual/en/language.variables.scope.php
In php curly braces don't necessarily define a new scope for variables. (your first example)
In your 2nd example, $b is only set on a specific condition. So it is possible to be 'undefined' if this condition is not met.
Shyam, you are using a scripting language, not C++. It is typical for scripting languages like PHP or JavaScript not to have different scopes for each code block. Instead there is one scope for the whole function. This is actually quite handy if you consider your first example, but you obviously need to be careful as can be seen in your second one.
is $a equals to 1? If not $b=2 will never be evaluated!
Actually your first method should be giving you an error too.
You're using a variable that hasn't been declared as an array. I can't understand why you didn't get an error for that.
PHP doesn't have block scope, so whether it's inside IF or FOREACH is irrelevant. If it's available inside the method, you can use it inside the method.

What's the proper term for converting a string into a variable/class/method?

I know it sounds so dumb but people were asking me about it and I don't have a proper answer.
Like
$var = "var1";
$var1 = "hello";
echo $$var;
Thanks!
You are talking about Variable variables :)
They're called variable variables.
It can be called "wrong program design" and "time to learn arrays"
The mechanism to specify a variable by using the value of another variable is called variable variables.
This might seem cool is some way. But I rather think that it’s an obscure technique and can also tempt to use some dangerous pattern like exporting input values to the global variable space (just like register globals does).
There are also some restrictions with variable variables:
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
This basically describes that the following is not possible:
$name = '_GET'; // identifier of the superglobal $_GET
$args = $$name;
But there’s also a workaround for this by using the $GLOBALS array:
$name = '_GET';
$args = $GLOBALS[$name];

PHP -What's the difference between global variables and constants

According to many sources, register_globals (global variables that is) should be disables in your php.ini.
Should I write define() in my code and use constants if global variables are disabled? Are those even related?
They are related in that they have global scope, but constants are meant to not change once defined, unlike global variables which the page can modify as it goes along. So just switching over to using define() instead of a global won't help much.
It's better if you refactor your methods to take the variables as parameters and rely on that to pass variables around.
Global variables aren't constant (you can change the value of a global variable, but you can only define a constant once).
Constants aren't always global (you can declare a constant in a class).
Also, global variables can be any type: scalar, array, or object. Constants can only be scalars.
I'm not going to say either constants or globals are good or bad. When used appropriately, they both have beneficial uses. There are security issues around the register_globals feature that are separate from more general use of globals.
A few things here.
First, the register_globals that you disable in your php.ini refers to an old PHP feature where any variable sent via a query string (GET) or form (GET/POST) would be converted into a global PHP variable. This is the functionality that is (and should be) disabled when you turn off register_globals. Even with this off, you can still define global variables in your application.
In general programming terms, global variables (not PHP's register_globals) are considered "bad" because when you encounter one as a programmer, you have no idea what other parts of the application might be using or changing it, or what effect your changes to that global might have. Also, if you're defining a new global variable, there's a chance you're going to overwriting an existing variable that someone else is relying on. When variables are defined locally (in a single function, or in other languages a single block) you can examine the local scope and usually determine what a change to that variable will do.
Constants, on the other hand, never change. You define them once, and they stay defined and no one can change them. That's why having global constants is considered "less bad" than having global variables.
Constants, once defined, cannot be changed.
Don't use constants as variables. If you need to use variables within functions, pass them into the function itself. Use everything in the way it was intended to be used. Variables are variable and Constants are constant.
Some constant examples:
<?php
// Certainly constant
define('MINUTES_PER_HOUR', 60);
define('DOZEN', 12);
// Constant, but specific to this application
define('GREETING', 'Dear %s');
define('TIMEOUT', 30);
// Configurable, but constant for this installation
define('DATABASE', 'mydb');
define('IMAGES_DIRECTORY', '/tmp/images');
// Not constant, or some other reason why can't be constant
$user = $_POST['userid'];
$days_of_week = array('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su');
?>
Something else to consider -- constants can't store things like arrays or objects, whereas something defined to $GLOBALS can be any variable type. So in some cases, if you need something to be global but it can't be stored to a constant by using define(), you might want to use $GLOBALS instead.
Also, register_globals and $GLOBALS are NOT the same thing!
You can change the global variable inside the function if both have a same name, because local variable override the global variable but does not change the value of global variable outside.in constant if you want to use same name variable in different function that not allowed to you and give a error,because it define one time and used in all program and you can not change the value of this variable in any function or block it is fixed value .
Try this simple test:
fileA.php:
<?php
define('SOMEVAL', 2);
?>
fileB.php:
<?php
if(defined('SOMEVAL')) echo SOMEVAL;
else echo "SOMEVAL does not exists\n";
include 'fileA.php';
if(defined('SOMEVAL')) echo 'SOMEVAL='.SOMEVAL;
else echo "SOMEVAL does not exists\n";
?>
Then run fileB.php and you'll see that before you include fileA.php, SOMEVAL is not defined. So what this means is that before you define anything, it won't be visible to the script.

Categories