Fatal error: Uncaught Error: Call to a Member Function query() on null in

Asked

Viewed 5,104 times

1

My class code Users

<?php 
    class Usuarios {
        function listar() {
            require_once 'controller/conexao.php';

            $sql = "SELECT * FROM usuarios";
            $usuarios = $mysqli->query($sql);

            while ($linhas = $usuarios->fetch_array()) {
                echo '<p>'.$linhas['id'].'</p>';
            } 
        } 

        function adicionar() {
            require_once 'controller/conexao.php';
        }
    }
?>

My code of model

<?php
    require_once('model/Usuarios.class.php');

    $user = new Usuarios();
    $user->listar();

    //$user->adicionar();
?>

My connection

<?php 
    define('SITE_URL', 'http://localhost/sistemas/objetos');

    $host = 'localhost';
    $user = 'root';
    $pass = '1';
    $db   = 'wellisson';

    $mysqli = new mysqli($host, $user, $pass, $db);
    $mysqli->set_charset('utf8');

    if ($mysqli->connect_error):
        echo "Erro na conexao: " . $mysqli->connect_errno . $mysqli->connect_error;
    endif;
?>
  • @13dev I am starting!

  • have you checked the file controller/conexao.php exists ? and is in the same directory that you indicated ?

  • is yes! if I use the code of the Usuarios class directly in my index.php , it runs smoothly

1 answer

2


Try to use dependency injection in class Usuarios , would look something like:

<?php 
    class Usuarios {

        /** @var \mysqli */
        protected $conn;

        public function __construct(\mysqli $conn) {
            $this->conn = $conn;
        }

        function listar() {
            $sql = "SELECT * FROM usuarios";
            $usuarios = $this->conn->query($sql);

            while ($linhas = $usuarios->fetch_array()) {
                echo '<p>'.$linhas['id'].'</p>';
            } 
        } 
    }
?>

Your model would be like:

<?php
    require_once('model/Usuarios.class.php');
    // $mysqli esta em conexao por isso tens de incluir aqui encima
    require_once('controller/conexao.php');

    // injectar a dependencia no construtor da classe
    $user = new Usuarios($mysqli);
    $user->listar();
?>
  • This way it worked right!

Browser other questions tagged

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