Page 1 of 1

Using variable in function created by another function

Posted: Thu Jan 13, 2011 6:14 pm
by jgille07
I am trying to write a function that queries a database based on using a MySQL entry ID as its argument and then using the contents of the resulting array of that query in another function.
Here is the code I have... I'm trying to figure out how to make it so I can use the $results variable from the db_edit function to create separate variables for each array row in the get_info function.
Any advice would be GREATLY appreciated... THanks

Code: Select all

<?php
class basics{
	
	public function db_edit($object_id){
		require('connection.php');
		$query = "select * from table where id = '".$object_id"' limit 0, 1";
		$results = $db->query($query);
		$db->disconnect();
	}
	
	public function get_info($category, $object_id){
		require('connection.php');
		$info_query = new basics();
		$info_query->db_edit(4);
		$row = &$results->fetchrow(MDB2_FETCHMODE_ASSOC);
		$object_title = $row['object_title_field'];		
		$db->disconnect();
	}

}
?>

Re: Using variable in function created by another function

Posted: Thu Jan 13, 2011 7:32 pm
by Neilos

Re: Using variable in function created by another function

Posted: Fri Jan 14, 2011 6:55 pm
by jgille07
I tried return but it didn't work... it resulted in the following error:
Fatal error: Call to a member function fetchrow() on a non-object in basics.inc

Any other ideas???

Code: Select all

<?php
class basics{

public function db_edit($object_id){
require('connection.php');
$query = "select * from table where id = '".$object_id"' limit 0, 1";
$results = $db->query($query);
return $results
$db->disconnect();
}

public function get_info($category, $object_id){
require('connection.php');
$info_query = new basics();
$info_query->db_edit(4);
$row = &$results->fetchrow(MDB2_FETCHMODE_ASSOC);
$object_title = $row['object_title_field'];
$db->disconnect();
}

}
?>

Re: Using variable in function created by another function

Posted: Fri Jan 14, 2011 7:40 pm
by jgille07
I tried it with and without the & before $results in the second function. Would this have something to do with variable scope or passing by reference?

Re: Using variable in function created by another function

Posted: Fri Jan 14, 2011 8:14 pm
by josh
The whole point of grouping functions into a class is so that they can share data. Passing thru a parameter is the "wrong" way. Using a class member is the "correct" way.

Code: Select all

class Foo
{ 
 protected $i = 1;

function add($number=1) 
{
 $this->i += $number;
}

function output()
{
 return $this->i
}
}

Code: Select all

$foo = new Foo;
$foo->add(1);
echo $foo->output(); // 2
$foo->add(3);
echo $foo->output(); // 5
Without class members, your functions would be having way too many parameters for other programmers to easily read the code.