好的,我已经掌握了编写类和方法的基础知识,并对它们进行了扩展。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();
我希望有人能帮助我在这里,我一直在寻找了几天,但似乎无法找到比其他任何信息基本上把它全部保存在一个类中,或者创建一个无限的扩展链 - 这没有什么帮助,因为虽然我希望所有的工作都通过一个“接口”来实现,但我仍然希望将这些“模块”分开。
我的道歉,如果这似乎太荒谬了不知何故 - 我是新手毕竟..
如果我理解正确...它不是“父”方法,但r ather“容器”方法。对于选项,通过'db_connect'中的方法(作为包装)和传递连接对象来暴露访问,或者当创建'db_user/db_post'对象时,传入''包含“它们的'db_connect'对象。快乐的编码。 – 2011-07-09 17:03:51