Search code examples
phpclasscategoriesclass-method

Not getting desired output from PHP class


This is my very first question actually. I am under a learning process of OOP PHP and trying to design my first class for Category. Here is my code

<?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; }

}

?>

Now, When i create its object from other file with a code as below:

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

The output gives me the correct catid when called getID(). But Shows NULL for getName() or any other function other than getID().

What am i doing wrong?

Thanks in advance


Solution

  • As @Arnold Gandarillas said, you are overwriting $datacol in the constructor.

    Your constructor calls load(), which sets $datacol:

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

    The function then returns true. In the constructor, this true is assigned to $datacol, overwriting the previous value:

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

    Change the constructor to something like this:

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