2011-07-09 131 views
1

好的,我已经掌握了编写类和方法的基础知识,并对它们进行了扩展。php - 一个对象可以引用父对象的方法吗?

我可以很容易地写出一个庞大的类,其中包含我可能想要的所有方法或者几个只是在链中相互延伸的类。但事情开始变得难以管理。

我想知道如果我可以做下面的代码,所以我可以保持“模块”分开,并且只在需要时才开启它。我希望这对我希望的某种意义有所帮助实现:

// user/member handling methods "module" 
class db_user 
{ 
    public function some_method() 
    { 
     // code that requires parent(?) objects get_something() method 
    } 
} 

// post handling methods "module" 
class db_post 
{ 
    public function some_method() 
    { 
     // code that requires parent(?) objects update_something() method 
    } 
} 

class db_connect() 
{ 
    public $db_user; 
    public $db_post; 

    public function __construct() 
    { 
     // database connection stuff 
    } 
    public function __destruct() 
    { 
     // blow up 
    } 

    // if i want to work with user/member stuff 
    public function set_db_user() 
    { 
     $this->db_user = new db_user(); 
    } 

    // if i want to work with posts 
    public function set_db_post() 
    { 
     $this->db_post = new db_post(); 
    } 

    // generic db access methods here, queries/updates etc. 
    public function get_something() 
    { 
     // code to fetch something 
    } 

    public function update_something() 
    { 
     // code to fetch something 
    } 
} 

,所以我会再创建一个新的连接对象:

$connection = new db_connect(); 

需要与用户如此工作..

$connection->set_db_user(); 
$connection->db_user->some_method(); 

现在我需要做的与职位,东西..

$connection->set_db_post(); 
$connection->db_post->some_method(); 
$connection->db_post->some_other_method(); 

我希望有人能帮助我在这里,我一直在寻找了几天,但似乎无法找到比其他任何信息基本上把它全部保存在一个类中,或者创建一个无限的扩展链 - 这没有什么帮助,因为虽然我希望所有的工作都通过一个“接口”来实现,但我仍然希望将这些“模块”分开。

我的道歉,如果这似乎太荒谬了不知何故 - 我是新手毕竟..

+1

如果我理解正确...它不是“父”方法,但r ather“容器”方法。对于选项,通过'db_connect'中的方法(作为包装)和传递连接对象来暴露访问,或者当创建'db_user/db_post'对象时,传入''包含“它们的'db_connect'对象。快乐的编码。 – 2011-07-09 17:03:51

回答

2

db_connectiondb_*类:

class db_user 
{ 
    protected $db; 

    public function __construct($db) 
    { 
     $this->db = $db; 
    } 

    public function some_method() 
    { 
     // code that requires parent(?) objects update_something() method 
     $this->db->update_something(); 
    } 
} 

用途:

$db = new db_connection(); 
$user = new db_user($db); 
$user->some_method() 

db_connect不应该有set_db_userset_db_post等,应当予以受理连接到数据库,也许一些通用选择/更新/插入/删除方法

+0

我认为这正是我所寻找的,像往常一样,我似乎对某件事情有太多的想法,结果徘徊在一条荒谬的道路上:) –

2

你可以传递一个参考db_connect到例如DB_USER/db_post构造函数,并将其存储到现场$parent

+0

我刚刚输入了相同的回应。绝对是使用现有代码的最简单途径。 – bioneuralnet

+1

注意:以这种方式获得循环链接,因此在应用程序停止之前不会调用析构函数。在大多数情况下,这没关系。 –

+1

“父母”对这个字段来说是相当错误的名字。 – Michas

相关问题