I can not access POST within my class in PHP

3

I have an HTML form with method="POST" and a submit button. Within my file 'purchases.controller.php', if I do a var_dump ($ _ POST), you can see all my POST variables belonging to the inputs of the form correctly.

Now, I have another file called 'aux.php' which gets an array through AJAX and then I pass it to a function of a class in the file 'purchases.controller.php'. There, I want to manipulate the array and the POST variables that are arriving, but it only allows me to manipulate the array, the POST within the function do not exist.

Does anyone know what I'm doing wrong?

I share the purchase code.controller.php:

//ACÁ ME MUESTRA LAS VARIABLES POST COMO EL 'registroUsuario', ETC.
var_dump($_POST)

    class Compras {

        public function ctrEfectivo(&$arrayCompleto){

            //ACÁ SE MUESTRA EL ARRAY CORRECTAMENTE
            var_dump("Muestro mi array dentro de la clase y función: ", $arrayCompleto);

            if(isset($_POST["registroUsuario"])){

                if(preg_match('/^[a-zA-ZñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["registroUsuario"]) &&
                   preg_match('/^([0-2][0-9]|3[0-1])(\/|-)(0[1-9]|1[0-2])(\d{4})$/', $_POST["registroCalendario"]) &&
                   preg_match('/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/', $_POST["registroEmail"]) &&
                   preg_match('/^(?:\D*\d){2,4}\D*$/', $_POST["registroDireccion"]) &&
                   preg_match('/^[0-9]{7,12}$/', $_POST["registroTelefono"])) {

                 //ACÁ QUIERO MANIPULAR TODO, PERO NO PUEDO YA QUE NO ESTÁN LLEGANDO LOS POST

    }

And here is the aux.php file:

if(isset($_POST['arrayCompleto'])){

include ('compras.controlador.php');

$arrayCompleto = json_decode($_POST['arrayCompleto'], true);

$nuevaCompra = new Compras();
$nuevaCompra -> ctrEfectivo($arrayCompleto);

}

This is the HTML form:

<form method="post" onsubmit="return validacionForm()" id="formCash">

    <input type="text" class="form-control" id="registroUsuario" name="registroUsuario" placeholder="Nombre Completo" maxlength="26" required>

    <input type="text" class="form-control" id="registroDireccion" name="registroDireccion" placeholder="Dirección de envío con altura de calle" required>

    <input type="text" class="form-control" id="registroCalendario" name="registroCalendario" placeholder="Día de envío" required>

    <input type="email" class="form-control" id="registroEmail" name="registroEmail" placeholder="Correo Electrónico" maxlength="32" required>

    <input type="text" class="form-control" id="registroTelefono" name="registroTelefono" placeholder="Teléfono de contacto" maxlength="16" onkeypress="return isNumber(event)" required>       

      <?php

      $compra = new Compras();
      $compra -> ctrEfectivo();

      ?>

    <input type="submit" class="btn btn-block btn-lg btn-default backColor btnPagar" id="btnPagar" value="CONFIRMAR PEDIDO">

</form>
    
asked by Damian Ricobelli 14.12.2018 в 01:55
source

1 answer

5

Damian note that you are creating an instance of the class, therefore, the content of $_POST , even if it is a super global will not be available in the class itself, nor should be (as superglobal), because we speak of two different areas.

Here it is necessary to understand something more about clases and Object Oriented Programming: the correct thing is to provide your method ctrEfectivo all the data he needs to work within it. If that method needs something more than what is in $arrayCompleto , you should simply pass it to that something else that he needs when you invoke the 1 method.

In other words: the POST data is available in the context where you create the instance of the class with new , and if you need them in some method of the class, you have to pass it from that scope.

In practice, it would be this:

class Compras {

    public function ctrEfectivo($arrData){

        //ACÁ SE MUESTRA EL ARRAY CORRECTAMENTE
        var_dump("Muestro mi array dentro de la clase y función: ", $arrData);

        if(isset($arrData["registroUsuario"])){

            if(preg_match('/^[a-zA-ZñÑáéíóúÁÉÍÓÚ ]+$/', $arrData["registroUsuario"]) &&
               preg_match('/^([0-2][0-9]|3[0-1])(\/|-)(0[1-9]|1[0-2])(\d{4})$/', $arrData["registroCalendario"]) &&
               preg_match('/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/', $arrData["registroEmail"]) &&
               preg_match('/^(?:\D*\d){2,4}\D*$/', $arrData["registroDireccion"]) &&
               preg_match('/^[0-9]{7,12}$/', $arrData["registroTelefono"])) {

             //ACÁ QUIERO MANIPULAR TODO, PERO NO PUEDO YA QUE NO ESTÁN LLEGANDO LOS POST

            }
        }
    }
}

If the method needs everything in the $_POST , you can pass the full POST to the method:

  /*Aquí creas la instancia de la clase con new*/
  $compra = new Compras();
  /*Aquí le pasas todo lo que hay en el POST, porque está disponible en ESTE contexto*/
  $compra -> ctrEfectivo($_POST);

Now, to avoid confusion, note that in the class I have called the parameter $arrData and that all the verifications I do are based on $arrData . You could leave $_POST , but you would be writing a very confusing code. Actually $arrData is the same as $_POST , but since super global POST does not exist in the context of the class, it exists (as $arrData ) because you passed it in parameter to the method.

That is, the classes are not any files, they are wrappers, representations of objects. When you use classes it is not that you link a file with another as you would with include or require , but you work with instances of objects to which you must provide what is necessary for their methods to do the work for which they are programmed.

What is the advantage of this? Many. For example, your class Compras represents a complete entity of your application, every time you go to work with purchases you can use it. You can give it several methods (the different functions that are done with a Compra ), you can map results from a table compras of the database, you can make complicated operations in different parts of the program with a single call to a Class method, you can relate it to other objects ... In short, OOP is another world and you also write a code thinking about the reality of life.

The response code is not perfect ... still the POST should be verified, it should not be empty, etc. And all your preg_match good, are a little afraid to see them, maybe that can be improved, but I do not want to get too much head. Here the important thing is to go a step further in understanding how classes and their methods work and or rather object-oriented programming itself.

  • That does not mean that everything has to be passed as a parameter to the method. Sometimes the classes have properties or fields inherent to them, and the methods, as members of the class, can make use of these properties without having to receive them in parameters from outside.
  • answered by 14.12.2018 / 12:53
    source