I am having some trouble learning how to use classes. I've tried looking up stuff online, read in books, and I can't figure out why this doesn't work. Here is the class: class artist{ //variables var $name; var $num_of_fans; var $link; var $desc; var $image; //constructor function artist($name) { global $cxn; global $t_artist; $query = "SELECT * FROM $t_artist WHERE name = \"$name\""; $result = mysqli_query($cxn,$query); $row = mysqli_fetch_assoc($result); $this->$name = $row['name']; $this->$num_of_fans = $row['num_of_fans']; $this->$link = $row['link']; $this->$desc = $row['description']; $this->$image = $row['image']; return; } function sayHi(){ echo "Hello!"; return; } } PHP: And here is where I construct it. I tried adding echo statements to the constructor, and they all came out fine, so I'm assuming that there is a problem with this part here: <?php $the_band = new artist("Metallica"); //these two lines don't do anything $the_band->sayHi(); echo $the_band->name; ?> PHP: Can someone help me out here?
Try class artist{ //variables var $name; var $num_of_fans; var $link; var $desc; var $image; //constructor function artist($name) { global $cxn; global $t_artist; $query = "SELECT * FROM $t_artist WHERE name = \"$name\""; $result = mysqli_query($cxn,$query); $row = mysqli_fetch_assoc($result); $this->name = $row['name']; $this->num_of_fans = $row['num_of_fans']; $this->link = $row['link']; $this->desc = $row['description']; $this->image = $row['image']; } function sayHi(){ $e = echo "Hello!"; return $e; } } PHP:
Try this code and see if it's work. class artist{ //variables var $name; var $num_of_fans; var $link; var $desc; var $image; //constructor function artist($name) { $mysqli = new mysqli ("yourserver", "username", "password", "yourdatabase"); //<----change this line to your setting $result = $mysqli->query("SELECT * FROM $t_artist WHERE name = \"$name\""); $row = $result->fetch_array(MYSQLI_ASSOC); $this->name = $row['name']; $this->num_of_fans = $row['num_of_fans']; $this->link = $row['link']; $this->desc = $row['description']; $this->image = $row['image']; $mysqli->close(); return; }//end constructor function sayHi(){ echo "Hello!"; return; } }//end class $the_band = new artist("Metallica"); //these two lines don't do anything $the_band->sayHi(); echo $the_band->name; PHP:
This should fix the problem. Just to elaborate, $this->name references a property of the object. $this->$name references a property of the object which $name evaluates to. $name is a variable. You could do this: $name = 'link'; Now these two are equal: $this->$name; $this->link;