简体   繁体   中英

PHP: Variable Scope Question/Referencing Variables

<?php
function table() {
   ot();
   for($x=0; $x<$rows; $x++) {  
   table_row($x);
}
   ct();
}
?>

Notice: Undefined variable: rows in .../scratch.php on line 12

Hi,

This function is returning an error because $rows is not defined locally. I define the variable $rows in another php script, which is referenced via "includes('includes.php')" at the top of this script file.

How do I pass or "reference" the variable $rows into this function? As you can tell, I'm still learning PHP and any help is greatly appreciated!

thx,

Define your function like this:

function table($rows) {
   ot();
   for($x=0; $x<$rows; $x++) {  
   table_row($x);
}

And then call it like this:

table($rows);

Where the $rows variable is defined in your calling script.

The other option would be to make $rows a global variable, in which case you can do:

function table() {
    global $rows;
    //etc
}

However, global variables should be avoided when possible, so I'd still recommend the first method.

if you want to use global variable withing the function you need to explicity declare it.

<?php
function table() {
    global $rows;
    for($x = 0; $x < $rows; $x++) {
        table_row($x);
    }
}

In most cases it is not a good idea to rely on globals and you should consider passing $rows as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM