About Object Oriented in PHP

Asked

Viewed 2,364 times

-4

I have my file php connection. 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);

There in my file banco.oo.php with the classes (object oriented) 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');
                }
        }
    }
}

There in my file index php. 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>

There 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);
}

So let’s have my question/problem:

I remember that before I didn’t need to take the variable $connected always in all $OO -> Signin($connected,$email,$passwd); because the same one was already pulling inside the file bank.oo.php when starting the class I think that as inheritance of the class all functions of it ended up receiving this variable that makes connect to the bank when calling the class, but now I don’t know what I did wrong in the database.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 my mistake in object orientation I made?

  • 2

    There is no OOP in this code. Separating into classes does not mean OO - besides, you will have trouble passing $conexao

2 answers

4

You can pass the connection only once, at the instantiation of the class, and store it on 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");
  • Thanks bfavaretto is exactly what I needed, now I remembered, when I get home I will etntar do and I return here on topic

2

TL;DR

Class methods are subject to scope restrictions such as functions. In order for a resource in the global, external scope to work in the local scope of the method, you have to globalize the variable (nay do it! ) or inject by means of a parking meter.


I will not go into the merit that what you have encoded has nothing to do with Object Orientation, so I attend only to the problem you have demonstrated, I suggest you read on Scope of Variables.

Methods of a class are functions, no use trying to argue. And if they are functions, they are subject to "limitations" (in quotes because it is not a de facto limitation) 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 variable scope $connection.

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

  • Um I’m going to look at that you told me

Browser other questions tagged

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