简体   繁体   中英

Why am I getting an “Undefined variable” notice in PHP?

So I have the following:

<?php
    show_form();
?>


<form id="add" method="post" action="addIssue.php">
    Name:
    <?php input_text('name','str_name', $defaults , '1'); ?>
    <input class="submit" type="submit" value="Begin download" />
    <input type="hidden" name="_submitCheck" value="1"/> 
</form>


<?php
function show_form($errors = '') 
{ 
    // If form is submitted, get the defaults from submitted parameters
    if(empty($_POST['_submitCheck']) OR !$_POST['_submitCheck'] ){
        // set our own defaults
        $defaults = array('str_name' => '');

    } else {
        $defaults = $_POST;
    }
} 

// Echo text box
function input_text($elem_id, $element_name, $values, $tab='') {
    echo '<input id="'.$elem_id.'" name="'.$element_name.'"';
    echo ' tabindex="'.$tab.'" class="text" value="';
    echo htmlentities($values[$element_name]) . '" />';
}
?>

Why am I getting the following Notice?

Notice: Undefined variable: defaults

$defaults is a local variable within the scope of the show_form function. You'll want to return it from the function and change your first line of code to this:

$defaults = show_form();

You need to set the variable to be global for that to work.

At the start of the show_form method, add this code:

global $defaults;

Or, a better solution as pointed out already is to return the variable and use $defaults = show_form().

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