tags:

views:

62

answers:

4

Please consider this example. (PHP)

class Database{  
    private $result;  
    private $conn;

    function query($sql){  
        $result = $this->conn->query($sql);  
        // Set the Database::$result ?? Or return the value and avoid setting property?  
        return $result;
        // $this->result = $result;  
    }  
}

what are the advantages of both these methods? Where are they applicable?

A: 

For a better class structure, i would suggest you to have a look at:

PHP Dependency Injection

This answers the most appropriate approach you may want to follow.

Sarfraz
+1  A: 

Based on your code I think it makes sense to return the result rather than set it as a property of the database class. A database (connection as it were) will have multiple result sets over its lifespan. So setting the result as a class property doesn't quite make sense if you're going to make multiple queries using the same object.

while a database connection might have multiple result sets, i ll only be saving the most recent result and the methods that are called afterwards will also use this. So i am still unclear :S
Shafee
A: 

Your recent comments indicate that you will only be keeping a single result set around at a time. This being the case, I would suggest saving it to the object itself (as a data member of the object).

Also, since you are only keeping around a single result set, you might rename your class to something more descriptive. "Database" doesn't quite summarize it. It is a "ResultSet". If it's a particular type of result set consider naming it so it reflects the type of data you are fetching.

A: 

I don't think the property belongs in Database, so do one of the following:

  1. return the query as is
  2. return a QueryObject which is already set with your query, but gives you additional methods to perform on the query result (for example: pagination, filtering)
chelmertz