Page 1 of 1
Adding functions to existing objects
Posted: Mon Aug 18, 2008 11:03 pm
by verycleanteeth
Hello! I'm a bit new to OOP and am trying to find a way to add functions to already existing objects. I'm pulling tables from a mysql "character" database with mysql_fetch_object, and these objects are organized just how I need them, except they lack the functions normally defined in the "character" class.
Thanks!
Re: Adding functions to existing objects
Posted: Tue Aug 19, 2008 9:20 am
by lukewilkins
So you are just wanting to add that object to the character class in order to use it with the methods (functions) there? If so: mysql_fetch_object() can hold 3 parameters (result, class_name, and params). So just do:
Code: Select all
mysql_fetch_object($result, 'character')
and the object will be added to the character class.
Hope that helps.
Re: Adding functions to existing objects
Posted: Tue Aug 19, 2008 1:57 pm
by verycleanteeth
So I've looked at
http://fr.php.net/mysql_fetch_object, and I understand adding that second parameter should work, but for the life of me I can't seem to get it to. I've set up a test page to try and figure out what I'm doing wrong. It looks like this:
Code: Select all
echo '<u>test page</u><br>';
require_once('dbconnect.inc.php');
class test
{
var $id;
var $name;
var $burger;
}
$query = "SELECT * FROM test WHERE id = '1'";
$result = mysql_query($query);
$test = mysql_fetch_object($result, 'test');
foreach ($test as $key => $value)
echo "$key - $value<br>";
echo '<br><u>end page</u>';
The output of this looks like:
test page
end page
But if I switch the line
Code: Select all
$test = mysql_fetch_object($result, 'test');
with
Code: Select all
$test = mysql_fetch_object($result);
I get:
test page
id - 1
name - gorgo
burger - meat
end page
I get all my info from the test table. Any idea what I'm doing wrong here? Is it something to do with my class definition?
Thanks for the help. It is MUCH appreciated.
Re: Adding functions to existing objects
Posted: Wed Aug 20, 2008 12:27 pm
by lukewilkins
So are you really wanting to use that class? 'Cause really you can just do this:
Code: Select all
$query = "SELECT * FROM test WHERE id = '1'";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
foreach ($row as $key => $value)
echo "$key - $value<br/>";
}
If this is just an example and you are wanting the class:
Code: Select all
class test {
public $id;
public $name;
public $burger;
public function display() {
echo 'id - '.$this->id.'<br/>';
echo 'name - '.$this->name.'<br/>';
echo 'burger - '.$this->burger.'<br/>';
}
}
require_once('dbconnect.inc.php');
$query = "SELECT id, name, burger FROM test WHERE id='1'";
$result = mysql_query($query);
while($row = mysql_fetch_object($result,'test')) {
$row->id;
$row->name;
$this->burger;
$row->display();
}
I didn't test that, but it should be right. mysql_fetch_object actually instantiates a new object of the class you specify.
Hope that helps.