Pass a constructor variable to another method

Asked

Viewed 47 times

0

I am using PDO and I want a constructor method with the database connection but the connection variable is not accessible in another method

class Stock{

public function __construct(){
    $conn= new PDO("mysql:host=localhost;dbname=caixa","root","");

}


public function listarTodosProdutos(){// seleciona todos produtos do Banco de dados e retorna

    $stmt=$conn->prepare("SELECT * FROM produtos");
    $stmt->execute();
    while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
        echo"Codigo:".$result["id"]." "."<br>"."Nome do Produto:   "."<b>".$result["nome"]."<br>"."</b>"." de valor de    ".$result["valor"]." Reais "."<br>"."da categoria    ".$result["descricao"]."</b>"."<br>"."---------------------------------------------------"."<br>";

    }

}

here is the other part I urge and call the method

<?php
require_once"Estoque.php";

$e=new Estoque();
$e->listarTodosProdutos();

?>

Error presented

Notice: Undefined variable: Conn in C: xampp htdocs Box made in Gabriel Stock.php on line

  • Use $this->conn

2 answers

0

Exactly as they said the solution is to put $this in the instance and assignment which becomes a global variable

    class Estoque{

public Function __Construct(){ $this->Conn= new PDO("mysql:host=localhost;dbname=box","root","");

}

public Function listarTodosProducts(){// selects all products from the Database and returns

$stmt=$this->conn->prepare("SELECT * FROM produtos"); $stmt->execute(); while($result = $stmt->fetch(PDO::FETCH_ASSOC)){ echo"Codigo:".$result["id"]." "."<br>"."Nome do Produto: "."<b>".$result["nome"]."<br>"."</b>"." de valor de ".$result["valor"]." Reais "."<br>"."da categoria ".$result["descricao"]."</b>"."<br>"."---------------------------------------------------"."<br>"; }

}

here is the other part I urge and call the method

Listall Products(); ?>

0

Locally instantiated variables that serve the class all must be called with

$this->variable that_wish

In your case $this->Conn

  • i changed put the $this-> in the constructor mode and keeps appearing the same error Notice: Undefined variable: Conn in C: xampp htdocs Box made in Gabriel Stock.php on line 8 and Notice: Undefined variable: Conn in C:xampp htdocs Box made in Gabriel Stock.php on line

  • Try something like this, declaring a variable, and then overriding its value with the constructor value public $Conn; public Function __Construct($Conn) { $this->Conn = $Conn; }

Browser other questions tagged

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