Fatal error: Uncaught Error: Call to a member function query () on null in

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 model code

<?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;
?>
    
asked by anonymous 11.08.2017 / 19:17

1 answer

2

Try to use 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 look 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();
?>
    
11.08.2017 / 19:38