开发者

which method is more efficient: set a class property; or return the result?

开发者 https://www.devze.com 2022-12-20 02:04 出处:网络
Please consider this example. (PHP) class Database{ private $result; private $conn; function query($sql){

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?


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.


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.


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消