How can I use the global keyword so that when I press the submit button I can set the global keyword so that the top part of the script works?
located on top of the script.
if(!isset($u)){
echo 'the $u has no value';
} else if(isset($u)){
echo 'the $u has a value of yes';
}
located on bottom of the script.
if (isset($_POST['submit'])){
global $u;
$u = 'yes';
}
global is related to scope, not to order of execution
If both pieces of code are global, i.e. are not contained into functions, the 'global' keyword has no effect, because they are in the same scope
As another answer has correctly pointed out, your problem is an order of execution problem, not a scope problem
That's not what global means. Global means that the variable can be accessed inside functions and the like. You probably want to use Sessions. This involves calling
sesssion_start();
somewhere (usually the top of your script).
Variables can then be stored and retrieved by doing
$_SESSION['name'] = $foo;//Store a variable into the session
$bar = $_SESSION['bar'];//Retrieve a variable from the session
In your case you would store u variable into the session and retrieve it after the submit.
Is there some reason you aren't just passing this value via the form?
You have to run the
if (isset($_POST['submit'])){
global $u;
$u = 'yes';
}
before the
if(!isset($u)){
echo 'the $u has no value';
} else if(isset($u)){
echo 'the $u has a value of yes';
}
PHP reads the code line by line, so isset($u) always return FALSE until the line $u = 'yes'; is run.
Related
I created a function to check for special characters in a string, but I can't seem to get it to echo the response message
Here is my code
<?php
function chk_string($string){
if (preg_match('/[\^£$%&*()}{##~?><>|=_+¬-]/', $string))
{
$chk_str="false";
} else {
$chk_str="true";
}
return $chk_str;
}
$string="this is just a test" ;
chk_string($string) ;
echo $chk_str;
?>
The "echo $chk_str" is not echoing anything.
If you did
$chk_str = chk_string($string);
then you could echo $chk_str;.
The $chk_str you are trying to echo is only visible in your function.
More description:
Your function (chk_string) is in a different scope than your echo.
Your function returns a variable, but that variable is "lost", since you don't assign it to another variable.
Your code currently does something like this line by line:
Your function declaration
$string means "this is just a test"
your functions result as a string, just floating in the code
write out a variable that doesn't exist.
I hope this helped in someway.
You need to store returned value in a particular variable if you want to echo that variable like this,
$chk_str = chk_string($string) ;
echo $chk_str;
Another way you can just directly echo returned value like this,
echo chk_string($string) ;
Your question is about variable scope and it is answered already, but I would recommend you to take a look at variable scope here https://www.php.net/manual/en/language.variables.scope.php.
Basically, every variable has its scope and we can not access a variable outside its scope. In your case, scope of variable $chk_str is inside function chk_string so you can not access it outside of the function. Because you return value of $chk_str in function chk_string so you still can access its value through response of function chk_string, for example:
echo chk_string('a string');
OR
$result = chk_string('a string');
echo $result;
When comparing the following scenarios, which one would be the fastest? Sample examplary code below.
Basically, what I'm trying to find out is what's the best alternative to using global vars.
The global vars that I store would be the same for all users... they are application level values which are the same for all users, application_name for example, or application_home_page_url...
I will have a ton of functions using these app level values and I do not want to pass them by argument, though I think that would be the fastest way.. My options seem to be working with either db look ups, or using session vars or globals..
Of course, you may take it to the next level by throwing the assoc. arrays into the equation to make it faster/?slower.
The other factor that we have to keep in mind is that we are talking about lots of users here.
So, what's the best way to toss around/work with these app level variables within individual functions?
//for global based approach
$my_global_var1 = "abc";
$my_global_var2 = "xyz";
//for global + array based approach
$my_globals['var1'] = "abc";
$my_globals['var2'] = "xyz";
//for session based approach
$_SESSION['my_global_var1'] = "abc"
$_SESSION['my_global_var2'] = "xyz";
//for session + array based approach
$_SESSION['my_globals']['var1'] = "abc";
$_SESSION['my_globals']['var2'] = "xyz";
//for db based approach
$varname = 'var1';
//or some other way, you may think of
//??
function func1()
{
global $my_global_var1;
global $my_global_var2;
//....
my_var1 = $my_global_var1;
}
function func2()
{
$my_var1 = $my_globals['var1'];
}
function func3()
{
$my_var1 = $_SESSION['my_global_var1'];
}
function func4()
{
$my_var1 = $_SESSION['my_globals']['var1'];
}
$my_var1 = func5($varname)
function func5($varname)
{
return lookup($varname);
}
I would suggest using a Registry class for this.
I'm sure there is more than one way to make such a class, but i prefer using a single static class:
class Registry {
private static $values = array();
public static function set($key, $value) {
self::$values[$key] = $value;
}
public static function get($key) {
return self::$values[$key];
}
}
Then you would just include the registry at the top of your application and interface it during with Registry::set('abc', 'xyz'); and Registry::get('abc');
A few links on this technique:
http://www.devshed.com/c/a/PHP/Registry-Design-Pattern/
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html#5
The idea behind global variables and session variables is different. Global variables are for using the same variable in a single script, regardless of scope. Session is to store variables for one user across pages. If I understand what you're trying to do correctly, it's probably better to use session variables.
Regarding the speed, try to measure your script's execution time with microtime(). You can use this (note: input not sanitized!):
<?php
$start = microtime(true);
if ($_GET['include']) { #include $_GET['include']; }
$end = microtime(true);
echo '<hr />';
echo 'The script executed in: '.(($end - $start)*1000).' milliseconds.';
?>
EDIT:
The comment to your post above me just made me understand better what you're trying to do. Indeed in case these variables are supposed to stay constant, use constants.
You should pass variables to functions if possible.
Example where Global variables are used:
<?PHP
$Variable = '1234567';
function funcName()
{
global $Variable;
echo $Variable;
}
?>
or you could just do
<?PHP
$Variable = '1234567';
funcName($Variable);
function funcName($varPassed)
{
echo $varPassed;
}
?>
SESSION variables are used to store a user-specific setting or variable across multiple page loads, or pages. They are used to store session information (username,password, last page), but you have complete control of it. Also SESSION variables are stored in temp files. If the stuff your storing are for individual users, then use SESSION...MySQL will clog up if not designed right with proper indexes and such.
I'm 'dissecting' PunBB, and one of its functions checks the structure of BBCode tags and fix simple mistakes where possible:
function preparse_tags($text, &$errors, $is_signature = false)
What does the & in front of the $error variable mean?
It means pass the variable by reference, rather than passing the value of the variable. This means any changes to that parameter in the preparse_tags function remain when the program flow returns to the calling code.
function passByReference(&$test) {
$test = "Changed!";
}
function passByValue($test) {
$test = "a change here will not affect the original variable";
}
$test = 'Unchanged';
echo $test . PHP_EOL;
passByValue($test);
echo $test . PHP_EOL;
passByReference($test);
echo $test . PHP_EOL;
Output:
Unchanged
Unchanged
Changed!
It does pass by reference rather than pass by value.
This allows for the function to change variables outside of its own scope, in the scope of the calling function.
For instance:
function addOne( &$val ) {
$val++;
}
$a = 1;
addOne($a);
echo $a; // Will echo '2'.
In the case of the preparse_tags function, it allows the function to return the parsed tags, but allow the calling parent to get any errors without having to check the format/type of the returned value.
It accepts a reference to a variable as the parameter.
This means that any changes that the function makes to the parameter (eg, $errors = "Error!") will affect the variable passed by the calling function.
It means that the variable passed in the errors position will be modified by the called function. See this for a detailed look.
I hava a function that looks something like this:
require("config.php");
function displayGta()
{
(... lots of code...)
$car = $car_park[3];
}
and a config.php that look something like this:
<?php
$car_park = array ("Mercedes 540 K.", "Chevrolet Coupe.", "Chrysler Imperial.", "Ford Model T.", "Hudson Super.", "Packard Sedan.", "Pontiac Landau.", "Duryea.");
(...)
?>
Why do I get Notice: Undefined variable: car_park ?
Try adding
global $car_park;
in your function. When you include the definition of $car_park, it is creating a global variable, and to access that from within a function, you must declare it as global, or access it through the $GLOBALS superglobal.
See the manual page on variable scope for more information.
Even though Paul describes what's going on I'll try to explain again.
When you create a variable it belongs to a particular scope. A scope is an area where a variable can be used.
For instance if I was to do this
$some_var = 1;
function some_fun()
{
echo $some_var;
}
the variable is not allowed within the function because it was not created inside the function. For it to work inside a function you must use the global keyword so the below example would work
$some_var = 1;
function some_fun()
{
global $some_var; //Call the variable into the function scope!
echo $some_var;
}
This is vice versa so you can't do the following
function init()
{
$some_var = true;
}
init();
if($some_var) // this is not defined.
{
}
There are a few ways around this but the simplest one of all is using $GLOBALS array which is allowed anywhere within the script as they're special variables.
So
$GLOBALS['config'] = array(
'Some Car' => 22
);
function do_something()
{
echo $GLOBALS['config']['some Car']; //works
}
Also make sure your server has Register globals turned off in your INI for security.
http://www.php.net/manual/en/security.globals.php
You could try to proxy it into your function, like:
function foo($bar){
(code)
$car = $bar[3];
(code)
}
Then when you call it:
echo foo($bar);
I had the same issue and have been tearing my hair out over it - nothing worked, absolutely nothing - until in desperation I just copied the contents of config.php into a new file and saved it as config2.php (without changing anything in its contents at all), changed the require_once('config.php'); to require_once('config2.php'); and it just started working.
The code below is just a sample of the format I have
isset($_GET['ids'])?$ids=$_GET['ids']:null;
isset($_POST['idc'])?$idc=$_POST['idc']:null;
function ShowCart()
{
$que = "SELECT
FROM
cart
LEFT OUTER JOIN ...
ON ...
LEFT OUTER JOIN... ON...
WHERE ";
$result = mysql_query($que);
while(){
if (isset($ids)) {
display something
for (){
if(){
} // end of if inside the for loop
}// end of for loop
}
elseif($idc && $ids=null) {
display something different
}
else{
display nothing has passed
}
}//end of while loop
}//end of showcart(); function
that's the formatting above I wonder why the if and elseif are not getting the isset() as the if and elseif argument.
I have debug the through the whole code and the print_r of GET and POST has values through the whole code.
print_r($_POST);
print_r($_GET);
Jona, if you'd ever bother to properly format your code, you'd see that the 'else' in question is WITHIN A FUNCTION, and you're defining $ids and $idc OUTSIDE THE FUNCTION. Remember, in PHP, global variables (except the super-globals, such as $_GET, $_POST, etc...) are not visible within functions unless you explicity define them as globals within the function.
Add global $idc, $idc; as the first line in the function definition and your if() will start working correctly.
Followup:
Your code is still hideously formatted, and very wonky. Take this:
isset($_GET['ids'])?$ids=$_GET['ids']:null;
You're using a trinary operator, but not assigning its results anywhere, and using the 'true' condition to do an assignment. This is an ugly hack. It should be written like this:
$ids = isset($_GET['ids']) ? $_GET['ids'] : null;
This way $ids will be set to null if there is no $_GET['ids']. Which brings up the fact that you're assigning a null instead of some other default value. If there really was no $_GET['ids'], then this:
$idx = $_GET['ids'];
would work identically, as PHP will automatically assign a null in situations where the right-hand-side doesn't exist. Of course, you still have to sanitize this value, since you're using it in an SQL query later on. Leaving it like this will just invite SQL injection attacks and all kinds of other abuses.
Beyond that, you're still creating $ids and $idc OUTSIDE of your ShowCart() function. As such, $ids and $idc within the function will be automatically be created with null values, since you've not declared them to be global. I think by now it's obvious you have no idea what this means, so try out this piece of code:
<?php
$var = 'Here I am!';
function showVar() {
echo "Within showVar(), var is set to: $var\n";
}
function workingShowVar() {
global $var;
echo "Within workingShowVar(), var is equal to: $var\n";
}
showVar();
workingShowVar();
If you copy/paste this code, run it, you'll see the following output:
Within showVar(), var is set to:
Within workingShowVar(), var is set to: Here I am!
Notice that both functions are identical, except for the global declaration. If you can figure out the difference, then you'll realize you need to re-write your ShowCart() function as follows:
function ShowCart() {
global $ids, $idc;
// rest of your code here
}
Well the code you've posted is sound, so it's probably a problem with the variables getting to that script in the first place. Are you sure those variables are defined in the GET string?
Dump out the contents of it to make sure:
print_r($_GET);
Try this:
$ids= isset($_GET['ids'])?intval($_GET['ids']):null;
$idc= isset($_GET['idc'])?intval($_GET['idc']):null;
if (isset($ids)) {
//display something
}
elseif(isset($idc)) {
//display something different
}
else
{
//display nothing has passed
}
I tested your script above,it works as expected.Maybe you should check whether the link is correct or not.