How to establish a communication, in the same file, between multiple PHP tags

Asked

Viewed 27 times

0

Good night. The point is, I’m doing a bank account program, where first, in a.html file, I retrieve some data via form, and send it to another file.php In this same, besides recovering the data typed by the user, I created an object "conta1", whose class is defined in another file Y.php. What I did now was close the php tag of the file, create a form for deposit or withdrawal of values, and open a new tag so that I recover this data, and perform the get and set operations with the object. The problem is that in this new tag the object "conta1" is not recognized, and so I would like to know how to solve it.

<?php
    
        $tipo_conta = isset($_GET["tipo_conta"]) ? $_GET["tipo_conta"]: null;
        $cpf_cliente = isset($_GET["cpf_cliente"]) ? $_GET["cpf_cliente"]: null;
        $nome_cliente = isset($_GET["nome_cliente"]) ? $_GET["nome_cliente"]: null;

        require_once 'Conta_bancaria.php';
        if($tipo_conta != null && $cpf_cliente != null && $nome_cliente != null){
            $conta1 = new Conta_bancaria($tipo_conta, $cpf_cliente, $nome_cliente, "não definida", null, true);
        }
        print_r($conta1);
        $conta1->setNum_conta("450-12");
        echo "<p> O número da conta foi definido e é {$conta1->getNum_conta()}.</p>";
        if($tipo_conta == "CC" || $tipo_conta == "cc"){
            $conta1->setSaldo(100);
        }
        else if($tipoconta == "CP" || $tipoconta == "cp"){
            $conta1->setSaldo(150);
        }
        echo "<p> Por ser um conta do tipo {$tipo_conta} o saldo inicial padrão é de {$conta1->getSaldo()}.</p>";
        echo "<p> Senhor(a) {$conta1->getDono()}, veja abaixo os dados atualizados de sua conta bancária: </p>";
        print_r($conta1);
    
    ?>
    </pre>
    
        <p id = "aviso"> Depósito ou saque </p>
        <form method = "get" action = "?"> 
            Se for depositar, informe o valor a ser depositado: <input type = "number" name = "deposito" /> </br>
            Se for sacar, informe o valor a ser sacado: <input type = "number" name = "saque" /> </br>
            <input id = "botao_enviar" type = "submit" value = "Enviar"/>
        </form> 
        
    <pre>
    <?php /* AQUI FAREI OPERAÇÕES DE MUDANÇA DOS DADOS DO SALDO COM OS VALORES DE DEPOSITO OU SAQUE */
        $deposito = isset($_GET["deposito"]) ? $_GET["deposito"]: null;
        $saque = isset($_GET["saque"]) ? $_GET["saque"]: null;
        require_once 'Conta_bancaria.php';
        
        if($saque == null && $deposito == null){
            echo "<p> Nenhum valor foi digitado </p>";
            exit();
        }
        else if($saque != null && $deposito != null){
            echo "<p> ERRO! Não é possível depositar e sacar simultâneamente </p>";
            exit();
        }
        else if($deposito != null && $saque == null){
            /* depositar*/
        }
        else if($deposito == null && $saque != null){
            /*sacar*/
        }
     ?>
  • I thought now about the possibility of passing the object of the first tag as "reference parameter" to a method of the class file, and recovering a "clone" of the object by calling the same function in the other tag. Would it be possible?

1 answer

0

Hello...

If you want to keep the object '$conta1' between requests, you will have to save it somewhere, possibly in this case, the ideal is the superglobal $_SESSION.

Do the following:

    // no começo do script
    session_start(); //para iniciar a sessão

    //antes de criar um objeto, veja se ele já existe. Se não existir, crie-o
    require_once 'Conta_bancaria.php';
    if(isset($_SESSION['conta']){
        $conta1 = $_SESSION['conta'];
    } else {
        if($tipo_conta != null && $cpf_cliente != null && $nome_cliente != null){
            $conta1 = new Conta_bancaria($tipo_conta, $cpf_cliente, $nome_cliente, "não definida", null, true);
            $_SESSION['conta'] = $conta1;
        }   
    } 
  • I’m learning PHP, I ended up wanting to take a few more steps during a video of getter Setter and constructor, bringing data insertion by HTML. But this solution you gave me I think I understood, in the session where I will make the getter and setters for deposit and withdrawal, which will be called for modification of the balance method, I defined that this same session will be equal to the previous session that was equaled to the object '$conta1'.

  • In the first PHP tag, I basically created the object, in the if Else code block, and did this: $_SESSION['account'] = $conta1; That’s what I understood from what you said. Already in the second PHP tag, where I will receive the deposit or withdrawal data, I did the following: session_start(); $_SESSION['dep_saq'] = $_SESSION['account']; That is, this new session will be the same as the previous session. That’s it?

  • More or less. The session is an object that persists on the server while the user is logged in. If there are no requests for a specified period, it expires, otherwise each time it is accessed, this period is renewed. Using it, you can 'transfer' or 'send/receive' data between pages/requests.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.