Why global is null in function? - php

I get this strange problem....
All the page has this code only.
global $currentPage; is null and i dont know why...
<?php
$pager = $_PARAMS["this"];
$pages = 5;
$currentPage = 1;
$tst="ap";
$nearPages = 5;
//Prologic
?>
<div class="pager">
<?php
$nearPagesHalf = ($nearPages - 1) / 2;
drawNumbers(1, 1);
if ($currentPage - $nearPagesHalf <= 0) {
}
drawNumbers($pages, $pages);
?>
<?php
function drawNumbers($from, $to) {
global $currentPage;
for ($i = $from; $i <= $to; $i++) {
echo $currentPage;
if ($i == $currentPage) {
?> <span class="pageNumbers current"><?= $i ?></span>
<?php
} else {
?>
<a href="#">
<span class="pageNumbers"><?= $i ?></span>
</a>
<?php
}
}
?>
<?php
}
function drawDots($from, $to) {
}
?>
</div>
THE PROBLEM
echo $currentPage; prints 1
function drawNumbers($from, $to) {
global $currentPage;
echo $currentPage; prints nothing

I bet you're executing this code by including this file inside another function.
So you need to mark the first variable occurrence as global too.
Btw, global variables are weird, the more simple and correct way to pass the data to the function is to use function parameters.

The $currentPage defined at the top does not live in global space. Why don't you just pass the $currentPage as the first parameter to the drawNumbers function? It's much cleaner that way:
drawNumbers( $currentPage, 1, 1 );
function drawNumbers($currentPage, $from, $to) {
// no need define $currentPage here since it's passed
}

I had a similar problem, but the solution is not on this page so I am putting here in order to help anyone who might show up looking.
My global variable was an object and it worked fine when calling the global vairable from a method AFTER the variable was defined.
class object{
function __construct($v1, $v2){
}
function methodA(){
global $a;
var_dump($a);
}
}
$a = new object($var1, $var2);
$a->methodA(); //Object...
However, when trying to use the global variable before the constructor has return it does not work.
class object{
function __construct($v1, $v2){
$this->methodA();//NULL
}
function methodA(){
global $a;
var_dump($a);
}
}
$a = new object($var1, $var2);
This looks like a dunce-cap situation, but my site is a lot more complex than this simplified scenario. So it took me a while to figure out that I was calling it before it was defined.

Related

How to declare global variables in php codeigniter 3.1.9?

I wrote a function with global variables, it works fine in normal run php but it does not execute in php codeigniter. Please check my code below and help me on how i should declare global variables in codeigniter 3.1.9
function getEmi($t)
{
global $i, $upto, $totalint, $rate, $monthly, $payment_date, $arr, $_SESSION, $tp;
$i++;
$r = $t*$rate; $p = round($monthly-$r); $e = round($t-$p);
if ($upto <= 0){ return 0; }
if ($upto == 2){ $_SESSION['tl'] = $e; }
if ($upto == 1){ $p = $_SESSION['tl']; $e = round($t-$p); $monthly = round($p+$r); }
$totalint = $totalint + $r; $tp = $tp+$monthly; $upto--;
echo '<tr><td>'.$i.'</td>';
$arrDate1 = explode('-', $arr[$i-1]);
echo '<td>'.date("d-M-Y", mktime(0,0,0,$arrDate1[1],$arrDate1[2],$arrDate1[0])).'</td>';
echo '<td>Rs.'.number_format(round($r)).'</td>';
echo '<td>Rs.'.number_format($t).'</td>';
echo '<td>Rs.'.number_format($p).'</td>';
echo '<td>Rs.'.number_format($monthly).'</td>';
echo '<td>Rs.'.number_format(round($e)).'</td>';
echo '</tr>';
return getEmi($e);
}
You can add your Global Variables in Constant File
File PATH: \application\config\constants.php
Or
You can add your Global Variables in Config File
File PATH: \application\config\config.php
define('ThemeColor', 'blue');//key and value
Now ThemeColor is your global variable you can use it in entire MVC pages, No need to write '$' before variable just use it as you wrote in define

Function doesn't save variable

I'm trying to add 1 to a number each time a function is called, but for some reason, the total number is always same.
Here is my current code:
<?php
$total;
function draw_card() {
global $total;
$total=$total+1;
echo $total;
}
draw_card();
draw_card();
?>
Personally, I would not use globals, but if I was forced at gunpoint I would handle state within the function, so outside variables did not pollute the value. I would also make an arbitrary long key name which I would not use anywhere else.
<?php
function draw_card($initial = 0) {
$GLOBALS['draw_card_total'] = (
isset($GLOBALS['draw_card_total']) ? $GLOBALS['draw_card_total']+1 : $initial
);
return $GLOBALS['draw_card_total'];
}
// optionally set your start value
echo draw_card(1); // 1
echo draw_card(); // 2
https://3v4l.org/pinSi
But I would more likely go with a class, which holds state by default, plus its more verbose as to whats happening.
<?php
class cards {
public $total = 0;
public function __construct($initial = 0)
{
$this->total = $initial;
}
public function draw()
{
return ++$this->total;
}
public function getTotal()
{
return $this->total;
}
}
$cards = new cards();
echo $cards->draw(); // 1
echo $cards->draw(); // 2
echo $cards->getTotal(); // 2
https://3v4l.org/lfbcL
Since it is global already, you can use it outside the function.
<?php
$total;
function draw_card() {
global $total;
$total=$total+1;
//echo $total;
}
draw_card();
draw_card();
draw_card();
echo "Current Count :", $total;
?>
Result :
Current Count :3
This will increment the number of times you call the function.
Since you echoed the result/total each time without a delimiter, you might have considered the output to be 12(Assumption)
Functions have a scope.. you just need to bring $total into the scope of the function... best to not do it globally but as an argument.
$total = 0;
function draw_card($total) {
return $total + 1;
}
$total = draw_card($total);
//Expected Output = 1
$total = draw_card($total);
//Expected Output = 2

PHP tables not printing out?

I'm calling a specific function, either getTaskList0, getTaskList1, or getTaskList2, each the same as below, with the number after task referring to the getTaskList number (in TaskManagerDAO):
function getTaskList0(){
$lst=array();
$con=$this->getDBConnection();
$result = $con->query("SELECT name, score FROM task0 ORDER BY score DESC");
$i = 0;
$counter=0;
while (($row =$result->fetch_row()) && ($counter<5)) {
$rec = new Task($row[0],$row[1]);
$lst[$i++]=$rec;
$counter++;
}
return $lst;
}
Task:
<?php
class Task{
public $name;
public $score;
function __construct($name,$score) {
$this->name = $name;
$this->score = $score;
}
}
The function is called in here:
<?php
session_start();
if(!class_exists('Action')){
include_once 'Action.php';
}
if(!class_exists('TaskManagerDAO')){
include_once 'TaskManagerDAO.php';
}
class Action_DisplayList implements Action{
public function execute($request){
if(!isset($_SESSION['functCount']))
$_SESSION['functCount']=0;
$functCount=$_SESSION['functCount'];
$functionName="getTaskList{$functCount}";
echo $functionName;
$dao = new TaskManagerDAO();
$names = $dao->$functionName();
$_SESSION['names'] = $names;
$last = sizeof($names);
$start = 0;
$_SESSION['start'] = $start;
$_SESSION['last'] =$last;
header("Location: tasklist.php");
}
}
?>
I'm trying to call the function by putting a variable at the end of the function name as a string and then calling the function. This works as I don't get any errors, but the list does not show up in the table, which is what this code is supposed to do:
<?php
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
include 'Action_Add.php';
Action_Add::execute();
}
$functCount=0;
$_SESSION['functCount']=0;
$names = $_SESSION['names'];
$start=$_SESSION['start'];
$last = $_SESSION['last'];
for($count = $start; $count < $last; $count++){
$name=$names[$count];
echo "<tr>";
echo "<td>".($count+1)."</td>";
echo "<td>".$name->name."</td>";
echo "<td>".$name->score."</td>";
echo "</tr>";
}
?>
EDIT:
I restarted my computer and everything and for the first run load of the page it worked perfectly. After that though, it stopped working though.
Use session_start(); before start using $_SESSION. So in your case, try something like
<?php
session_start();
if(isset($_POST['Add']) && ($_POST['name']!=="") &&!empty($_POST['Add'])){
//.... remaining code here
Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser.

How can I access a variable inside another function?

I have two functions that print some values. I need to use the variable $mv in the second function. However, $mv can only be defined in the first function. I have tried all types of PHP global examples and none of them has allowed the $mv variable to be used or visible or accessible in the second function.
function printMobilePrev(&$mobileprevresults) {
if (count($mobileprevresults->getRows()) > 0) {
$mv = $mobileprevRows[0][0];
$mobileprevRows = $mobileprevresults->getRows();
echo '<p>Previous period (sessions): '.$mobileprevRows[0][0].'..............................';
} else {
print '<p>No results found.</p>';
}
}
function printMobileCurr(&$mobilecurrresults) {
if (count($mobilecurrresults->getRows()) > 0) {
$mobdiff = ($mobcur - $mv);
$mobpctchg = ($mobdiff / $mobprev) * 100;
$mobilecurrRows = $mobilecurrresults->getRows();
echo '<p>Previous period (sessions): '.$mobileprevRows[0][0].'..............................';
echo '<p>Previous period (sessions): '.$mv.'..............................';
echo '<p>Current period (sessions): '.$mobilecurrRows[0][0].'..............................';
if ($mobdiff > 0){
echo '<p>Percent increase: '.$mobpctchg.'..............................';
} else {
echo '<p>Percent decrease: '.$mobpctchg.'..............................';
}
} else {
print '<p>No results found.</p>';
}
}
You can use the global scope:
That is what you want to do:
$mv = 0;
function function1()
{
global $mv;
$mv = 'whatever';
//code
}
function function2()
{
global $mv;
// use $mv;
}
You have to predefine that variable OUTSIDE any function, and then you can use Global to get that to any function.
You can pass it by reference. For example
function doSomething(&$mv) {
$mv = 1;
}
function doSomethingElse($mv) {
return $mv;
}
$mv = 0;
doSomething($mv);
echo doSomethingElse($mv); //Output: 1
You could return $mv after your print and save that in a var to pass to the next function:
$printMobilePrev = printMobilePrev();
function printMobilePrev(&$mobileprevresults) {
$mv = $mobileprevRows[0][0];
...
print '<p>No results found.</p>';
return $mv;
...
}
$printMobileCurr = printMobileCurr(&$mobilecurrresults,$mv);
function printMobileCurr(&$mobilecurrresults,$mv) {
......
}
Most likely you have to make a correct use of globals.
declare your $mv variable as global before asigning it a value on your first function
global $mv;
$mv = $mobileprevRows[0][0];
use global at the begining on your second function before using it
function printMobileCurr(&$mobilecurrresults) {
if (count($mobilecurrresults->getRows()) > 0) {
global $mv;

Creating random string using function within loop returns strange output (PHP)

I hope this issue hasn't been addressed in another thread - did some searching but found nothing.
I am writing a function to create some randomized comments in the form of a string. It's going to be used in a loop context in production. I wrote a while loop to test the function and I'm getting some strange output. It works great on the first loop but each subsequent loop truncates the strings to their first chars.
<?PHP
$prefix=array();
$prefix[]="Wow! That's";
$prefix[]="That's";
//...
$prefix[]="Amazing image. So";
$prefix[]="Wonderful image. So";
$suffix=array();
$suffix[]="amazing";
$suffix[]="awesome";
//...
$suffix[]="fabulous";
$suffix[]="historic";
$punctuation=array();
$punctuation[]='!';
$punctuation[]='!!';
//...
$punctuation[]='.';
$punctuation[]='...';
function comment() {
global $prefix;
$prefix_max=count($prefix)-1;
$rand=rand(0,$prefix_max);
$prefix=$prefix[$rand];
global $suffix;
$suffix_max=count($suffix)-1;
$rand=rand(0,$suffix_max);
if(strpos(strtolower($prefix),strtolower($suffix[$rand])) > 0) {
$rand=$rand+1;
if($rand > $suffix_max) {
$rand=0;
}
}
$suffix=$suffix[$rand];
if(substr($prefix, -1) == '.' || substr($prefix, -1) == '!') {
$suffix=ucfirst($suffix);
}
$rand=rand(1,100);
if($rand < 18) {$suffix=strtoupper($suffix);}
global $punctuation;
$punctuation_max=count($punctuation)-1;
$rand=rand(0,$punctuation_max);
$punctuation=$punctuation[$rand];
$comment=$prefix.' '.$suffix.$punctuation;
return $comment;
}
$i=0;
while($i < 70) {echo comment()."\r\n"; $i++;}
?>
This is the output from the loop:
Thank you for sharing! That's wonderful...
T w.
T w.
T w.
T w.
T w.
T w.
T w.
T W.
T W.
T W.
T W.
...
I was expecting full different strings like the first returned value from the loop. Any thoughts on why it's getting truncated?
This is because you're using global, and your comments() function is changing the arrays into strings
e.g
global $prefix; // references the global variable $prefix
// which is initially defines as an array
$prefix_max=count($prefix)-1;
$rand=rand(0,$prefix_max);
$prefix=$prefix[$rand]; // changes the value of the global variable
// $prefix to a string
And this is one of the main reasons why the use of global is so strongly discouraged
You are overwriting the prefix and suffix array.
Try this:
<?PHP
$prefixArray=array();
$prefixArray[]="Wow! That's";
$prefixArray[]="That's";
//...
$prefixArray[]="Amazing image. So";
$prefixArray[]="Wonderful image. So";
$suffixArray=array();
$suffixArray[]="amazing";
$suffixArray[]="awesome";
//...
$suffixArray[]="fabulous";
$suffixArray[]="historic";
$punctuation=array();
$punctuation[]='!';
$punctuation[]='!!';
//...
$punctuation[]='.';
$punctuation[]='...';
function comment() {
global $prefixArray;
$prefix_max=count($prefixArray)-1;
$rand=rand(0,$prefix_max);
$prefix=$prefixArray[$rand];
global $suffixArray;
$suffix_max=count($suffixArray)-1;
$rand=rand(0,$suffix_max);
if(strpos(strtolower($prefix),strtolower($suffixArray[$rand]))!==FALSE) {
$rand=$rand+1;
if($rand > $suffix_max) {
$rand=0;
}
}
$suffix=$suffixArray[$rand];
if(substr($prefix, -1) == '.' || substr($prefix, -1) == '!') {
$suffix=ucfirst($suffix);
}
$rand=rand(1,100);
if($rand < 18) {$suffix=strtoupper($suffix);}
global $punctuation;
$punctuation_max=count($punctuation)-1;
$rand=rand(0,$punctuation_max);
$punctuation=$punctuation[$rand];
$comment=$prefix.' '.$suffix.$punctuation;
return $comment;
}
$i=0;
while($i < 70) {echo comment()."<BR>"; $i++;}
?>

Categories