doutan2111 2011-10-04 16:31
浏览 16
已采纳

类变量 - 何时使用它们

How does one know when to put variables into the class rather than inside the class functions? For example - This database class is instantiated by its sub-class and it also instantiates its sub-class. It has no class variables.

class database extends one_db      
{
    function __construct()  
    {
        one_db::get();
    }

    public function pdo_query()
    {
    }

    public function query($query) 
    {
        return one_db::$db->query($query);
    }

    private function ref_arr(&$arr)  // pdo_query will need this later. 
    { 
        $refs = array(); 
        foreach($arr as $key => $value) 
        {  
            $refs[$key] = &$arr[$key];
        } 
        return $refs;
    }   
}

Howeve I could just as well pull out the $query variabe like this

class database extends one_db      
{
    protected $query;

    function __construct()  
    {
        one_db::get();
    }

    public function pdo_query()
    {
    }

    public function query($query) 
    {
        $this->query=$query
        return one_db::$db->query($this->query);
    }

    private function ref_arr(&$arr)  // pdo_query will need this later. 
    { 
        $refs = array(); 
        foreach($arr as $key => $value) 
        {  
            $refs[$key] = &$arr[$key];
        } 
        return $refs;
    }   
}

I would assume that this only needs to be done when the variable is shared between multiple class functions but I'm not too sure.

  • 写回答

2条回答 默认 最新

  • dongshenling6585 2011-10-04 16:37
    关注

    There are 3 types on variables to be used in a class/object:

    1. An instance variable - to be used as an object-wide variable, which all methods should have access to. Saving a databse connection is a good idea for an instance variable.
    2. A static variable - to be used when there is no need for an object instance. A static counter of some some sort is usually a static variable.
    3. A method variable - which is only contained within its function. Internal methodical variables should go in this category.

    Your choice depending on your needs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了