1

I am trying to create a function that can set a variable of id, name and url for 3 categories. I wanted to use one function do them all

$this->set_variables('main,con,feat');

function set_variables($cats) {
    $cats = explode(',',$cats);
    foreach($cats as $cat) {
        $this->$cat.'_id' = $cat;
        $qry = mysqli_query($this->con,"SELECT categories_name,categories_url FROM categories WHERE categories_id=$this->$cat.'_id'");
        $row = mysqli_fetch_assoc($row);
        $this->$cat.'_name' = $row['categories_name'];
        $this->$cat.'_url' = $row['categories_url'];
    }
}

So by the end of it, $this->main_id, $this->main_name, $this->main_url, $this->con_id, $this->con_name, etc... will all be set variables. But I am struggling with finding a way to include the variable, I have tired:

$this->$cat.'_id'
$this->[$cat]_id
$this->{$cat}_id

And various other attempts, but dont seem to be able to get any of them to set. So how do I set these variables?

Source
  • 1,026
  • 4
  • 11
  • 23

0 Answers0