0

Please consider this class, I have an html page with two forms, first i submit form1 and after that I submit second one. I change $aaa value in first function but after submitting second form, it show empty array and lost assigned value in func1.
I want to access func1 assigned value in func2.

class Myclass
{
    private $aaa = array();

    public function func1() {
        $this->aaa= [1, 2, 3];
    }

    public function func2() {
        var_dump($this->aaa);
    }
}

In the HTML file:

<form action=" FUNC1 " method="post" id="form1">
    <button type="submit">FUNC1</button>
</form>

<form action=" FUNC2 " method="post" id="form2">
    <button type="submit">FUNC2</button>
</form>
4
  • 7
    php is stateless, it won't automatically maintain data between form posts. You have to find a way to maintain application state yourself, by saving data to a database, a session, or passing it back and forth with the client. Commented Sep 30, 2016 at 20:30
  • 1
    as Mark H. said, as PHP is stateless when you load the controller again for the second form you will lose the values. I would suggest using func1() to save the data to the session if you are working with sessions. Commented Sep 30, 2016 at 20:34
  • What is the best way to pass an array? Is session a good way? Commented Sep 30, 2016 at 20:35
  • 2
    Session is a good way. There isn't just one "best" way, though. Commented Sep 30, 2016 at 20:43

1 Answer 1

1
class MyClass
{

public function __construct(
    $closure
) {
    $this->aaa = $closure();
}

public function func1() ....

You can now hold your data inside a session individual to that users browser

session_start();
$myClass = new MyClass(function () use($_SESSION) { if(isset($_SESSION['index_here'])) { return $_SESSION['index_here']; } });

Then the same when appending or changing the object property aaa - update the session

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.