Не получается желаемый вывод из класса PHP

Это мой самый первый вопрос на самом деле. Я нахожусь в процессе обучения ООП PHP и пытаюсь создать свой первый класс для категории. Вот мой код

<?php
class category{

public  $catid;
public $datacol;

public function __construct($catid=0)
{
$this->catid=0;
$this->datacol=$this->load($catid);
}

public function load($catid)
{
global $conn;
$sql=' select * '
.' FROM tbl_categories'
.' WHERE catid='.$catid;
if (!($res=mysqli_query($conn,$sql)) || !mysqli_num_rows($res)>0)
return false;
$this->datacol = mysqli_fetch_array($res);
$this->catid = $this->datacol['catid'];
return true;
}

public function reload() {
return $this->load($this->getId());
}

/* ------------------> Getter methods <--------------------- */
public function getId() { return $this->catid; }
public function getName() { return $this->datacol['category']; }
public function getOneliner() { return $this->datacol['categoryoneliner']; }
public function getBrief() { return $this->datacol['categorybrief']; }
public function getThumb() { return $this->datacol['timg']; }
public function getImage() { return $this->datacol['limg']; }
public function getParentID() { return $this->datacol['parentcat']; }
public function getPagetitle() { return  $this->datacol['catpagetitle']; }
public function getKeywords() { return $this->datacol['catkeywords']; }
public function getMetadesc() { return $this->datacol['categorymetadesc']; }
public function getPriority() { return $this->datacol['priority']; }
public function getRemarks() { return ($this->datacol['remarks']); }
public function getRow() { return $this->datacol; }

}

?>

Сейчас,
Когда я создаю его объект из другого файла с кодом, как показано ниже:

$cat=new category(10);
echo var_dump($cat);
echo var_dump($cat->getId());
echo var_dump($cat->getName());

Вывод дает мне правильный catid при вызове getID (). Но показывает NULL для getName () или любой другой функции, кроме getID ().

Что я делаю неправильно?

заранее спасибо

-1

Решение

Как сказал @Arnold Gandarillas, вы перезаписываете $datacol в конструкторе.

Ваш конструктор вызывает load(), который устанавливает $datacol:

public function load($catid)
{
...
$this->datacol = mysqli_fetch_array($res);
return true;
}

Затем функция возвращает true, В конструкторе это true назначен на $datacol, перезаписывая предыдущее значение:

public function __construct($catid=0)
{
$this->catid=0;
$this->datacol=$this->load($catid);
}

Измените конструктор на что-то вроде этого:

public function __construct($catid=0)
{
if ($catid > 0)
$this->load($catid);
}
1

Другие решения

Хорошо — присмотритесь к своей функции:

public function load($catid)
{
global $conn;
$sql=' select * '
.' FROM tbl_categories'
.' WHERE catid='.$catid;
if (!($res=mysqli_query($conn,$sql)) || !mysqli_num_rows($res)>0)
return false;
$this->datacol = mysqli_fetch_array($res);
$this->catid = $this->datacol['catid'];
return true;
}

Итак, ваша функция возвращает либо true из false, И это булево значение назначено $this->datacol Вот:

$this->datacol = $this->load($catid);

Как это назначение происходит после ты сделал $this->datacol = mysqli_fetch_array($res);, ваш $this->datacol становится либо правда или же ложный, и не содержит никаких реальных данных из MySQL.

Так, один Из решений можно снять назначение:

public function __construct($catid=0)
{
$this->catid=0;
$this->load($catid);
}

В этом случае ваш $this->datacol не перезаписывается

0

его простой $ this-> datacol = $ this-> load ($ catid); не требуется

вы присваиваете $ this-> datacol дважды

 public function __construct($catid=0)
{
$this->catid=0;
$this->load($catid);
}
public function load($catid)
{
global $conn;
$sql=' select * '
.' FROM tbl_categories'
.' WHERE catid='.$catid;
if (!($res=mysqli_query($conn,$sql)) || !mysqli_num_rows($res)>0)
return false;
$this->datacol = mysqli_fetch_array($res);
$this->catid = $this->datacol['catid'];
return true;
}

пожалуйста, добавьте, если чего-то не хватает

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector