GorillaApe
GorillaApe

Reputation: 3641

Why global is null in function?

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

Upvotes: 13

Views: 13792

Answers (3)

Albert
Albert

Reputation: 122

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.

Upvotes: 0

zerkms
zerkms

Reputation: 254906

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.

Upvotes: 38

Luke
Luke

Reputation: 21236

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
}

Upvotes: 5

Related Questions