0

I have a function called in the beginning of my php page and it is being called in the block of php but not further down in the html form. How far is the scope for a php function and how can I extend it to include it in the html form?

Here is an example of my code: Edit: This is NOT my actual code. It is simply showing where the scope of the function is not reaching.

<?php
function foo(){
    $x = 1;
    return $x;
}

if (isset($_POST['submit1']) and ! empty($_POST['submit1'])){
    $x = foo();

}
?>

<div>
    <form action="" method="POST">
        <input type='submit' name='submit1' value='Submit'>
    </form>
</div>
<div>
    <form action="" method="POST">
        <?php
        $x = foo();
        echo "<input type='text' value='".$x."'>";
        ?>
        <input type='submit' value='Submit' name='submit2'>
    </form>
</div>

The first instance of the function is called, but not the second. Can someone explain to me why. and do I need to create the function again in the second form or is there a way to extend the scope of the first function. Thank You!

Edit: This is not a function inside of a function like the linked question. This is a separate php instance where I would like to access the original function.

8
  • What is the initial value of $x, or how you set the value $x in foo() Commented Jan 3, 2017 at 17:57
  • It can be anything. @developer in my case it is actually an array Commented Jan 3, 2017 at 17:58
  • inside the form, what you expect from the <?php $x = foo(); ?> to be? Commented Jan 3, 2017 at 17:59
  • @developer I would like to create an input in the form which will reflect a value in the function Commented Jan 3, 2017 at 18:01
  • If you don't define namespaces, functions are global. Your problem are global variables (and you don't need them at all). Commented Jan 3, 2017 at 18:01

1 Answer 1

3

Your code is a bit confusing because no matter which value $x has in the beginning $x will always be undefined (notice: undefined index).

function foo(){
    return $x;
}

There is no $x and the outer scope will not be accessed.

function foo($x){
    return $x;
}

or

function foo() use ($x) {
    return $x;
}

or

function foo(){
    global $x;
    return $x;
}

... the outer scope will be accessed.

Sign up to request clarification or add additional context in comments.

3 Comments

I like this answer because this use global and use. This work fine with PHP5 and PHP 7. I recommend this answer.
@OlafErlandsen Globals are a terrible idea
Yes @Machavity, but this answer has 4 scope ways ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.