Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why global is null in function?

Tags:

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
like image 219
GorillaApe Avatar asked Nov 02 '10 03:11

GorillaApe


2 Answers

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.

like image 130
zerkms Avatar answered Sep 27 '22 16:09

zerkms


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
}
like image 38
Luke Avatar answered Sep 27 '22 17:09

Luke