About Object Oriented in PHP

-4

I have my connection.php file with the code below:

$banco_hostname = "localhost";
$banco_usuario="root";
$banco_passwd="";
$banco_nome="banquinho";
$conexao = new mysqli($banco_hostname,$banco_usuario,$banco_passwd,$banco_nome);

In my banco.oo.php file with the (object-oriented) classes I have:

class autenticacao {
    function SignUp($conexao,$nome_post,$email_post,$passwd_post,$k_post,$k) {
        if( (!$nome_post) || (!$email_post) || (!$passwd_post) || (!$k_post) || ($k_post != $k) ){
            header('location:index.php');
        }
        else{
                // VERIFICA SE USUARIO OU EMAIL EXISTE CADASTRADO
                $sql = $conexao->query("SELECT email FROM usuarios WHERE email='$email_post'");
                if ($sql->num_rows==1){
                    echo '<div class="alertaIndexMSG">Ocorreu um erro, este e-mail ja possui um cadastro no banco de dados...</div>';
                }
                else {
                    $acessos=1;
                    $ip=$_SERVER["REMOTE_ADDR"];
                    // INSERE USUARIO AO BANCO DE DADOS
                    $sql = $conexao->prepare("INSERT usuarios SET nome = ?, email = ?, passwd = ?, ip = ?, acessos = ?");
                    $sql->bind_param('ssssi',$nome_post,$email_post,$passwd_post,$ip,$acessos);
                    $sql->execute();
                    $_SESSION["message-signup"]=TRUE;
                    $_SESSION["autenticado"]=$email_post;
                    $_SESSION["usuario"]=$nome_post;
                    header('location:index.php');
                }
        }
    }
}

In my index.php file I would have a form for SignUp as an example

<html>
<head>
<meta charset="UTF-8">
<title>Titulo</title>
</head>
<body>
 <!-- FORMULARIO DE SIGN UP AQUI -->
</body>
</html>

In my file that processes the SignUp form I have:

include("conexao.php");
include("banco.oo.php");
if (isset($_POST["signin"])){
    $email=$_POST["email"];
    $passwd=md5($_POST["passwd"]);
    $OO = new autenticacao();
    $OO -> SignIn($conexao,$email,$passwd);
}

Let's then ask my question / problem:

I remember that before I did not need to carry the $ connection variable always throughout $ OO - > I'm not sure how to do this, but I'm not sure how to do this, but I'm not sure how to do this. connect to the bank when calling the class, but now I do not know what I did wrong in the banco.oo.php that every time I call a function I have to leave taking this variable and getting it there in the function to connect to the bank. >

What error in object orientation did I make?

    
asked by anonymous 31.07.2014 / 07:50

2 answers

4

You can only pass the connection once, in class instantiation, and save it in a property. Something like this:

// Nomes de classe costumam ter iniciais maiúsculas
class Autenticacao {

    // Propriedade
    private $conexao;

    // Construtor
    function Autenticacao($conexao) {
        $this->conexao = $conexao;
    }

    // Exemplo de uso em um método qualquer
    function dados($sql) {
        return $this->conexao->query($sql);
    }
}

// Instanciação e uso
$auth = new Autenticacao($conexao);
$auth->dados("SELECT 1");
    
31.07.2014 / 14:40
2

TL; DR

Class methods are subject to scope constraints such as functions. In order for a resource in the global scope, external, to work in the local scope of the method, you have to globalize the variable ( not do this!) Or inject by a parameter.

I will not go into the merit that what you have encoded has nothing to do with Object Orientation, so, if I only stick to the problem you've demonstrated, I suggest you read about Variable Scope .

Methods of a class are functions, no use trying to argue. And if they are functions, they are subject to the "limitations" (in quotation marks since there is a limitation in fact) of scope, local and global.

Most likely "before it worked" because there was no class involved or somehow you located (not in the sense of finding) the scope of the variable $ connection .

You almost did right by injecting the connection instance into the class instead of using the global keyword or the superglobal $ GLOBALS array. You erred as to where, instead of having been in the method, it should have been in the class constructor, assigning it to a property, so it would be available to all methods of the class without the need to inject every time, in each method.

    
31.07.2014 / 14:43