PHP - Global Var And Functions
I have some variables that I have set with the global command but they don't seem to be working correctly. It's probably my order of operation but not sure. Here's the stripped down version of whats going on:
locator() //functions function geoip() global $zip, $city, $areacode, $metrocode, $state, $country, $latitude, $longitude; function locator() geoip() use globals from geoip pass to- ad_display() function ad_display() does some work stat_tracking() function stat_tracking() access global $zip, $city, $areacode, $metrocode, $state, $country, $latitude, $longitude; The problem is once I call stat_tracking() and try to access the global variables, they are all empty. Just to clarify the chain of events is: page loads, calls locator(), locator() calls function geoip() fine then passes work to ad_display(), ad_display() calls stat_tracking(), stat_tracking() now tries to access the globals I made but all variables are blank if I echo them. Any ideas? Similar TutorialsHi, In all my classes, I need to declare globals for everything else, from site variables even to objects (other classes). I obviously don't want to as globals are horrible and I need to have functions clean without globals. I have included a list of all the global vars in the construct and it still doesn't work. Example: start.php <?php $vars = array(some values); $some = more; $variables = foo; $helper = new Helper(); $home = new Home(); This is a little bit simplistic, but for some reason, the variables just don't want to go in the main class without a global. Functions will not run if they require any of these variables. Hi, As the title suggests I am unsure on how to first run a query which stores values into an array. I then need to run a function multiple times but use the array within the function. How is this possible? I have had no luck figuring it out yet. 1. RUN QUERY 2. BUILD ARRAY USING QUERY RESULTS 3. RUN FUNCTION MULTIPLE TIMES 4. WITHIN FUNCTION I NEED TO USE ARRAY Many thanks Simon I have a script I am putting together that simulate a cricket game. The only issue is, that there are a huge number of functions because there doesn't seem to be any other way to do this properly. As well as this, there a while() loop and all this seems to be leading to the page reaching a max 30 second timeout when generating the result. My code is attached below, it is quite messy at the moment because i've just be working on it, but I was wondering if anyone has any solutions of how I can speed this up or change to prevent a timeout: <?php // Error reporting error_reporting(E_ALL); // Connect DB mysql_connect("wickettowicket.adminfuel.com", "rockinaway", "preetha6488") or die(mysql_error()); // Select DB mysql_select_db("wickettowicket") or die(mysql_error()); // MySQL queries to find batsmen and bowlers $array_batsmen = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 1 ORDER BY id ASC'); $array_bowlers = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 2'); // Start table for data $data = '<table width="600px">'; // Create blank scorecard while ($array_bat = mysql_fetch_array($array_batsmen)) { $data .= '<tr><td>'.$array_bat['name'].'</td><td></td><td></td><td>0</td></tr>'; } // Set up arrays for players $current_batsman = $current_bowler = array(); // Reset query mysql_data_seek($array_batsmen,0); $in_one = $in_two = $it = ''; function currentBatsman($id, $name, $ability, $strength, $out, $in, $runs) { global $current_batsman; $current_batsman = array ( 'id' => $id, 'name' => $name, 'ability' => $ability, 'strength' => $strength, 'out' => $out, 'in' => $in, 'runs' => $runs ); echo 'set current'; } // Set up arrays of batsmen while ($array = mysql_fetch_array($array_batsmen)) { if ($it < 3 && $in_one == '') { currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_one = $array['id']; $current = $array['id']; $it++; } else if ($it < 3 && $in_two == '') { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_two = $array['id']; $it++; } else { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 0, 'runs' => 0 ); } } // Bowler Array while ($array = mysql_fetch_array($array_bowlers)) { $bowlers[] = array ( 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'] ); } // Reset both queries mysql_data_seek($array_bowlers,0); mysql_data_seek($array_batsmen,0); function changeBatsman($just_out) { global $array_batsmen, $batsmen; //Update array $batsmen[$just_out] = array ( 'in' => 1, 'out' => 1 ); while ($array = mysql_fetch_array($array_batsmen)) { if ($just_out != $array['id'] && $batsmen[$array['id']]['out'] != 0) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'change batsman'; } function swapBatsman($other_batsman) { global $array_batsmen, $batsman; while ($array = mysql_fetch_array($array_batsmen)) { if ($other_batsman != $array['id'] && $batsman[$array['id']]['out'] != 0 && $batsman[$array['id']]['in'] == 1) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'swap batsman'; } $runs = $outs = $balls = $overs = 0; $played = array(); function selectBowler() { global $bowlers, $current_bowler; // Select random bowler $choose_bowler = array_rand($bowlers, 1); $current_bowler = array ( 'name' => $bowlers[$choose_bowler]['name'], 'ability' => $bowlers[$choose_bowler]['ability'], 'strength' => $bowlers[$choose_bowler]['strength'] ); } /* function selectBatsman(); { global $array_batsmen; while ($array_batsmen[]['out'] != 1) { }*/ function bowl() { global $batsmen, $bowlers, $current_bowler, $current_batsman, $data, $balls, $outs, $runs; if ($current_batsman['out'] == 0) { echo 'bowling'; // Set the initial number $number = rand(0, 190); // Ability of batsman if ($current_batsman['ability'] > 90) $number += 30; else if ($current_batsman['ability'] > 70) $number += 15; else if ($current_batsman['ability'] > 50) $number += 2; else $number = $number; // Strength of batsman if ($current_batsman['strength'] > 90) $number += 15; else if ($current_batsman['strength'] > 70) $number += 10; else if ($current_batsman['strength'] > 50) $number += 5; else $number = $number; // Depending on overs if ($balls > 270) $number += 30; else if ($balls > 120) $number -= 10; // Ability if ($current_bowler['ability'] > 90) $number -= 30; else if ($current_bowler['ability'] > 70) $number -= 15; else if ($current_bowler['ability'] > 50) $number -= 2; else $number = $number; // If batsman has made a huge total of runs, we need to knock some numbers off - more likely to get out if ($current_batsman['runs'] > 200) $number -= 70; else if ($current_batsman['runs'] > 100) $number -= 30; // Finally sort out runs if ($number > 190) $run = 6; else if ($number > 170) $run = 4; else if ($number > 160) $run = 3; else if ($number > 100) $run = 2; else if ($number > 50) $run = 1; else if ($number > 10) $run = 0; else if ($balls > 120 && $number > 0) $run = 0; else $run = -1; // Increase number of balls $balls += 1; // Are they out? if ($run == -1) { $current_batsman['out'] = 1; $played[] = $current_batsman['id']; $find = '<tr><td>'.$current_batsman['name'].'</td><td></td><td></td><td>0</td></tr>'; $replace = '<tr><td>'.$current_batsman['name'].'</td><td></td><td>'.$current_bowler['name'].'</td><td>'.$current_batsman['runs'].'</td></tr>'; $data = str_replace($find, $replace, $data); changeBatsman($current_batsman['id']); echo 'out'; } else { $current_batsman['runs'] += $run; $runs += $run; if ($run == 1 || $run == 3) { swapBatsman($current_batsman['id']); echo 'time to swap'; } echo $run; } // Count outs if ($current_batsman['out'] == 1) $outs += 1; } } function game() { global $main, $batsmen, $bowlers, $data, $batted, $balls, $outs, $current_batsman; // Check if possible while ($balls <= 295 && $outs < 10) { selectBowler(); // Actually bowl now bowl(); } } game(); echo $data; This question may sound very lame... ... But I have never able to know how to define a variable that I can use in different functions in a same file. There is no class structure just a PHP file with some functions. Is it possible to use some type of variable that can be share by all functions and that variable should not be a session variable . Something like: <?php $my_global_var; function A() { // use $my_global_var here } function B() { // use $my_global_var here and should retain the last value } ?> Something like in VB6.... Thanks Just wanted to know if $_Session was a global thing or does php require cookies setup?
I assumed that I could do something like this:
PAGE: A.php session_start(); $_Session['Cat'] = 'Meow'; // ----------------------- PAGE: B.php if (isset($_Session['Cat']) && !empty($_Session['Cat'])){ echo $_Session['Cat']; } OUTPUT: Meow // ----------------------- PAGE: C.php if (isset($_Session['Cat']) && !empty($_Session['Cat'])){ echo $_Session['Cat']; } OUTPUT: MeowI can't seem to get this to work. Page: Handler.inc // ========================================================= Session Log in / out public function logon($username, $password){ if ($username == "admin" && $password == "coffee"){ session_start(); $_SESSION['USER_STATUS'] = '1'; echo 'IN SESSION LOGIN HANDLER'; echo $_SESSION['UserLogged']; } } public function logout(){ $_SESSION['USER_STATUS'] = '0'; echo 'IN SESSION LOGOUT HANDLER'; session_destroy(); //session_unset(); }Page: index.php if (!isset($_SESSION['USER_STATUS']) && empty($_SESSION['USER_STATUS']) || $_SESSION['USER_STATUS'] == 0){ if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])){ $username = $_POST['username']; $password = $_POST['password']; echo $handler->logon($username, $password); } <LOGIN FORM CODE> }else{ if (isset($_SESSION['USER_STATUS']) && !empty($_SESSION['USER_STATUS']) || $_SESSION['USER_STATUS'] == 1){ echo 'Session name: '. $_SESSION['USER_STATUS']; } if (isset($_POST['btn_logout']) && !empty($_POST['btn_logout'])){ $handler->logout(); echo '<br />Logged out<br />'; } <LOGOUT FORM BUTTON CODE> }Could someone point me in the right direction please. It does not seem to hold its session. I use $db object to handle database function like $db->get_row for example. Is there any way that I don't need to put into every function global $db or do I actually need to repeat in every function global $db? Code: [Select] function example(){ global $db //Do I need to repeat this in each function? } It's a function=> Code: [Select] function _wp_call_all_hook($args) { global $wp_filter; //var_dump($wp_filter); //exit(); reset( $wp_filter['all'] ); do { foreach( (array) current($wp_filter['all']) as $the_ ) if ( !is_null($the_['function']) ) call_user_func_array($the_['function'], $args); } while ( next($wp_filter['all']) !== false ); } Why is $wp_filter variable declared as global ? Was $wp_filter assigned before ? hello, ok if i set a Global on index.php (wwwroot/admin/index.php) it works Code: [Select] $page1='hello from page1 on index'; global $page1; echo $page1; i can echo $page1 on other pages like (wwwroot/admin/pages/home.php) and it will echo out "hello from page1 on index". GREAT but if i write a Global on (wwwroot/admin/pages/home.php) it does not work. i also can not echo it out on any other page Code: [Select] $page2='hello from page2 on home'; global $page2; echo $page2; why is this ??? i have two classes and I am trying to call one class in through another here is my code but my welcome is not showing at all ever when i change the var's to 1 Code: [Select] class site { function DisplayContent ($page) { global $Users; echo '<div align="center"> <div id="Header"> <div id="NavBar">'; if ($Users->logged == 1) { echo 'Welcome '. $Users->user .' - <a href="?page=viewreminders">View Reminders</a> - <a href="?page=addreminder">Add Reminder</a> - <a href="logout.php" id="Logout">Logout</a>'; } else { echo '<a href="?page=login">Login</a> - <a href="?page=register">Register</a> - <a href="?page=forgotpassword">Forgot Password?</a>'; } echo '</div> </div> <div id="Content">'; $this->ShowPage($page); echo '</div> <div id="Footer">Copyright © '.date('Y').'<br /> Coded and Designed by Chris Cloyd</div> </div>'; } } class users { var $logged; var $user; var $email; var $level; function LogIn ($name,$email,$level) { $this->logged = 1; $this->user = $name; $this->email = $email; $this->level = $level; } function LogOut () { $this->logged = "0"; $this->user = ""; $this->email = ""; $this->level = ""; } } I teaching myself php, but I am coming from java and other compiled languages, so the process has been a little bumpy. I am trying to do something like this: Code: [Select] class my_class { function one () { $two = two (); $three = three (); $five = $two + $three; return $five; } function two () { $two = 2; return $two; } function three () { $three = 3; return $three; } } Unfortunately, I keep getting an error message saying that my call to two () is an undefined function. I am gathering from this that the scope of one () is not aware of the existence of two (). Is there a way to get around this so I can call two () and three () from one ()? Hey, I've been developing a browsergame. In this you are able to produce something ("weed"). Now I've got some kind of trouble with the function that is responsible for updating the "weed" on the user accounts. Im going to explain, how my script is working First step: Loading the datas from "worlds". In this case id, weed_factor, weed_basis. What this is required for you will see in the next steps <?php include 'includes/settings/mysql.php'; mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbbase); $time = time(); $update_weed_world_data_sql = "SELECT id, weed_factor, weed_basis FROM worlds"; $update_weed_world_data_res = mysql_query($update_weed_world_data_sql) OR DIE (mysql_error()); while($update_weed_world_data_while = mysql_fetch_assoc($update_weed_world_data_res)){ $update_weed_world_id = $update_weed_world_data_while['id']; $update_weed_world_basis[$update_weed_world_id] = $update_weed_world_data_while['weed_basis']; $update_weed_world_factor[$update_weed_world_id] = $update_weed_world_data_while['weed_factor']; global $update_weed_world_basis; } Second step: This is the function which is editing each account by the data given as parameters. function do_update_weed($profile_id,$world,$update,$level,$time){ $update_weed_period = $time - $update; $update_weed_add = ($update_weed_period / 3600 * $update_weed_world_basis[$world] * pow($update_weed_world_factor[$world],$level)) +1; echo $update_weed_world_basis[$world]; echo "<br>"; mysql_query("UPDATE profiles SET weed = weed +$update_weed_add, weed_update = $time WHERE id = $profile_id LIMIT 1"); } Note: echo $update_weed_world_basis[$world]; doesnt result an output. In step three, the accounts are loaded: function todo_update_weed($time){ $todo_update_weed_sql = "SELECT * FROM profiles WHERE weed_update < $time"; $todo_update_weed_res = mysql_query($todo_update_weed_sql) or die (mysql_error()); while($todo_update_weed_while = mysql_fetch_assoc($todo_update_weed_res)){ do_update_weed( $todo_update_weed_while['id'], $todo_update_weed_while['world_id'], $todo_update_weed_while['weed_update'], $todo_update_weed_while['level_farm'], $time ); } } And the last step is calling function "todo_update_weed" with the time. todo_update_weed($time); I script calculate the time between the last update and the current time. This make a difference in time. With this value I calculate something else. And then the update time has to be saved. The script has just working fine, when I set the variable "$update_weed_add" with a fix value. But by now the script doesn't work, because I don't know how to make the array available inside functions. I considered whether I put the database-function for the world_data inside the function that updates the profiles. But if I do this, the database will be called thousands of times... Hope anybody has a nice idea to fix the problem Through out my program I have used global $mysqli; as a connection to my database - this has worked fine so far. Now I have called $sql_statement = "SELECT * FROM items WHERE name='$itemName'"; $itemStats = mysqli_fetch_array(mysqli_query($mysqli, $sql_statement), MYSQLI_ASSOC); via a function and I get the following warnings - Quote Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /functions/getdata.php on line 27 Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /functions/getdata.php on line 27 it still works though and returns the correct information. If I take the code out of the function and use it normally then I get no Warnings - but this defeats the whole purpose of having functions! How do I get rid of the warnings? (and no, I don't mean turn the warnings off ) I know there is a function for this, but for some reason my google-fu is off and I cannot remember it for the life of me. What is the function to export an array into the global namespace? Such that: $var=array('key'=>'val'); somefunc($var); echo $key; Would work? Hi there, I am a highly concerned about ever using global variables (as many guides I have seen on security issues with PHP say you should avoid them, kind of understand why though to be fair), but I was wanting to really understand custom based session handlers in PHP and this first one he http://uk.php.net/manual/en/function.session-set-save-handler.php on the example: 'Example #1 session_set_save_handler() example' uses them. Now would it be better to take the global variable in function: ''open()' and then return the variable $sess_save_path then pass it up to the next function that may need it perhaps? I just don't want to use globals if I can avoid it, been working out a system that work use for some old solution we use and it uses globals and it really bugs the living life out of me, why people are so lazy they can't avoid them at all costs grrr. Any advice generally speaking is of great appreciation, Jeremy. <?php function getglobal() { global $my_global; echo "The value of \$foobar is '$foobar' <br />"; } $my_global = 20; getglobal(); ?> It's supposed to give the result, Quote 'The value of $my_global is '20'; But instead when I try it, its giving me Quote Notice: Undefined variable: foobar in C:\wamper\www\php\index.php on line 17 The value of $foobar is '' So I don't really understand what's happening and why it's not working. This topic has been moved to CSS Help. http://www.phpfreaks.com/forums/index.php?topic=356577.0 $errors=0; //NEW USER NAME HAS BEEN SUBMITTED, CHECK IT OUT AND THEN ADD IF OKAY $newuser=$_REQUEST['newuser']; function TryAgain(){ global $errors; $errors++; echo '<br/><br/>Please try again <a href="index.php?locate=admin&sub=add_admin">here</a>'; echo "<br/>errors=[$errors]"; } echo "<br/>Trying to add user: $newuser<br/><br/>"; if ($newuser){ }else{ // field was left blank, report this to user and give them option to try again echo '<br/>Field was left empty, you must pick a username.';TryAgain(); } if (strlen($newuser)<5){echo 'Username should be at least 5 characters.';TryAgain();} if (!$errors){echo "continue to SQL [errors=$errors]";} what is wrong with this code? For some reason if I increment $errors with $errors++ within the function it doesn't increment outside the function's scope. even though I declare it as a global at the start of the function. I know I'm doing something stupid here but can somebody please tell me what it is? Thanks Hiya! I was wondering if this is possible. Here is my example. This is a example class; <?php class a { public function __construct() { } public function returnValue() { include 'files/lang.php'; $this->lang = new lang(); return $this->lang->displayLang('10'); } } ?> This is the second class file; <?php class b { public function __construct() { } public function returnValue() { include 'files/lang.php'; $this->lang = new lang(); return $this->lang->displayLang('10'); } } ?> This is the main file; <?php include 'test/a.php'; $test = new a(); $test->returnValue(); include 'test/a.php'; $test2 = new b(); $test2->returnValue(); ?> With this I'm getting an error stating I cannot redeclare the function lang. I have found a way around this by using require_once but I was wondering if remove the include and $this->lang var from class 2 and I put this as the $this->lang var declaration in class 1; global $this->lang = new lang(); will class 1 and class 2 be able to use it from only the one declaration made in class 1. If so, would this be the way to do it or is there a better/working way to do it? Many many thanks, James. Can someone tell me what some of the purposes of this would be? global $PHP_SELF; its defined right after a function like this function myFunction(module =' '){ global $PHP_SELF; .... } Thanks |