简体   繁体   中英

php variable scope inside a loop in a function

I am wondering is there any way to get the value of a variable, that was defined in a loop inside a function?

Do variables declared in a loop / if-then-else, etc have a limited scope (only inside these blocks)?

here is an example of a function:

<?php

function getComments($tabName) {
    $sql = "select
                a.owner,
        a.table_name,
        a.column_name,
        a.data_type,
        a.data_length,
        a.data_precision,
        b.comments
            from 
                all_tab_columns a,
        user_col_comments b
            where 
                a.TABLE_NAME = b.table_name
        and a.COLUMN_NAME = b.column_name
        and a.owner = 'CORE' 
        and a.table_name ='" . $tabName . "'
            order by 
                a.column_id";
    $stid = oci_parse(getConnect(), $sql);

    // runs the query above                   
    oci_execute($stid);
    while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
        foreach ($row as $column => $entry) {
            // Column name
            if ($column == 'COLUMN_NAME') {
                $output = "this is a column";
            }
        }
    }

    return $output;
}

And here I get the "Undefined variable: output" error.

if I put echo instead the $output variable, I get the result.

Is it because the $output scope? How can I get the $output value in my return?

try to satisfy this condition

        if ($column == 'COLUMN_NAME') {
            $output = "this is a column";
        }

and also u can try to return immediately after ur condition

        if ($column == 'COLUMN_NAME') {
            return "this is a column";
        }

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