Estoy desarrollando una aplicación con herencias de objetos. Al querer crear un nuevo objeto no lo crea. Al querer obtener el id de un objeto me devuelve:
Fatal error: Call to a member function getId() on a non-object.
Código donde llamo a getId()
:
<?php
$controller = new TextController();
$c = $controller->getAllText();
?>
<h1> blog X</h1>
<a href="afegircontingut.html">afegir contingut</a>
<?php
while($c){?>
<h2><?=$c->getId();?></h2>
<p><?=$c->getContingut();?></p>
El código que genera el objeto es este:
public function getAllText(){
$this->connect();
$s = $this->_conn->prepare("SELECT * FROM content");
$s->execute();
$result = $s->get_result();
$rows = array();
while($row = $result->fetch_assoc()) {
array_push($rows,$this->createTextFromAssoc($row));
}
return $rows;
}
private function createTextFromAssoc($arr){
$text = new Text($arr['id'], $arr['titol'], $arr['data'], $arr['autor'], $arr['tipus'], $arr['contingut']);
return $text;
}
interfaz ContentInterface.php:
<?php
interface ContentInterface {
public function getId();
public function setId($id);
public function getTitol();
public function setTitol($titol);
public function getData();
public function setData($data);
public function getAutor();
public function setAutor($autor);
public function getTipus();
public function setTipus($tipus);
public function getContingut();
public function setContingut($contingut);
}
clase abstracta ContentAbstract.php:
class ContentAbstract implements ContentInterface{
protected $id;
protected $titol;
protected $data;
protected $autor;
protected $tipus;
protected $contingut;
public function __construct($id = null, $titol = null, $data= null, $autor = null, $tipus = null, $contingut= null)
{
$this->setId($id);
$this->setTitol($titol);
$this->setData($data);
$this->setAutor($autor);
$this->setTipus($tipus);
$this->setContingut($contingut);
}
public function getId(){
return $this->id;
}
public function setId($id){
$this->id= $id;
}
public function getTitol(){
return $this->titol;
}
public function setTitol($titol){
$this->id= $id;
}
public function getData(){
return $this->data;
}
public function setData($data){
$this->id= $id;
}
public function getAutor(){
return $this->autor;
}
public function setAutor($autor){
$this->autor= $autor;
}
public abstract function getTipus();
public abstract function setTipus($tipus);
public abstract function getContingut();
public abstract function setContingut($contingut);
}
classe Text.php:
class Text extends ContentAbstract{
public function __construct(){
parent::__construct();
}
public function getTipus(){
return "text";
}
public function setTipus($tipus){
$this->tipus= $tipus;
}
public function getContingut(){
return "contingut text";
}
public function setContingut($contingut){
$this->contingut= $contingut;
}
}
getId
. El mensaje de error: Fatal error: Call to a member function getId() on a non-object indica que en alguna parte estás llamando dicho método desde una instancia no válida del objeto.