Goodmorning everyone. I coded a class that return me:
Notice: Undefined variable: db in /Applications/MAMP/htdocs/Test Vari/index.php on line 12
Fatal error: Call to a member function row() on null in /Applications/MAMP/htdocs/Test Vari/index.php on line 12
This is the first part of the php file:
session_start();
$_SESSION['ID'] = 1;
require_once 'pass/password.inc.php'; /*Here's the DB Class*/
I extended a class into another, here's the code:
class pg extends DB{
public $id;
function __construct(){
parent::__construct();
$this->id = $_SESSION['ID'];
}
public function pgname(){
$rs = $db->row("SELECT CONCAT(Nome, ' ', Cognome) FROM Personaggio WHERE id = :id",array("id"=>$this->id));
return($rs);
}
}
$pg = new pg();
print_r ( $pg->pgname());
The $db->row() is declared in DB class that I extended, and I know for sure that's working. The DB class isn't initialized, and when I do, the error is the same, this is how I do it:
class pg extends DB{
public $id;
public $db;
function __construct(){
parent::__construct();
$this->db = new DB();
$this->id = $_SESSION['ID'];
}
public function pgname(){
$rs = $db->row("SELECT CONCAT(Nome, ' ', Cognome) FROM Personaggio WHERE id = :id",array("id"=>$this->id));
return($rs);
}
}
The Fatal Error will disappear when I delete braces in print_r($pg->pgname);
您必须require_once'DB.php'
The first way is just fine, but you need to remember that you are calling $db->row(
as it exists in the parent class you need to use $this->
on it so
class pg extends DB{
public $id;
function __construct(){
parent::__construct();
$this->id = $_SESSION['ID'];
}
public function pgname(){
$rs = $this->row("SELECT CONCAT(Nome, ' ', Cognome) FROM Personaggio WHERE id = :id",array("id"=>$this->id));
return($rs);
}
}
$pg = new pg();
print_r ( $pg->pgname());
Also to keep the encapsulation of the class nice and tight, it would be better to pass the session to the constructor rather than get it from the $_SESSION inside the constructor like this :
class pg extends DB{
public $id;
function __construct($id){
parent::__construct();
$this->id = $id;
}
public function pgname(){
$rs = $this->row("SELECT CONCAT(Nome, ' ', Cognome) FROM Personaggio WHERE id = :id",array("id"=>$this->id));
return($rs);
}
}
$pg = new pg($_SESSION['ID']);
print_r ( $pg->pgname());
I also assume you have included the file containing the DB
class?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.