PHP类树,其中父类保存子类的实例


PHP Class tree where parent holds instances of the subclasses

我有一个主类:" a ",它的构造函数接受一个web服务的可选登录名和密码。我有A: A1、A2和A3的子类,它们具有用于同一公司的其他web服务的方法。它们都使用相同的登录名和密码,但有不同的用途。每个都有自己的一组方法。

所以,如果我已经有了父类(或任何子类)的实例,我如何创建其他子类而不必重新验证父类?

我想这样做:

class A {
    protected static $authenticated_service_handle; //Takes a while to set up
    protected $instance_of_A1;
    function __construct($login = null, $password = null) {
        //Go do login and set up
        $authenticated_service_handle = $this->DoLogin($login, $password)
        //HELP HERE: How do I set up $this->instance_of_A1 without having to go through construction and login AGAIN??
        //So someone can call $instance_of_A->instance_of_A1->A1_Specific_function() ?
    }
}
class A1 extends A {
    function __construct($login = null, $password = null) {
        parent::__construct($login, $password);
    }
    public function A1_Specific_function() {
    }
}
//How I want to use it.
$my_A = new A('login', 'password');
$method_results = $my_A->instance_of_A1->A1_Specific_function();
$second_results = $ma_A->instance_of_A2->A2_Specific_function();

有什么办法自然地做到这一点吗?这似乎有点落后于标准的OO方法,但我的调用客户端将需要同时使用A1、A2和A3的方法,但是方法的数量和它们的组织使它们能够根据功能分解成子类。

如果你在类A中创建的东西是一个可以被所有需要它的类使用的连接,你可以这样使用它:

class ServiceConnection
{
    private $_authenticated_service_handle; //Takes a while to set up
    function __construct($login = null, $password = null) {
        //Go do login and set up
        $_authenticated_service_handle = $this->DoLogin($login, $password)
    }
    public function DoSomething()
    {
        $_authenticated_service_handle->DoSomething();
    }
}

并将该连接传递给所有需要它的对象:

$connection = new ServiceConnection('login', 'password');
$my_A1 = new A1($connection);
$my_A2 = new A2($connection);
$my_A3 = new A3($connection);
$my_A1->A1_Specific_function();
$my_A2->A2_Specific_function();
$my_A3->A3_Specific_function();

an类看起来像这样:

class A1 {
    private $_connection;
    function __construct($connection) {
        $_connection = $connection;
    }
    public function A1_Specific_function() {
        $_connection->doSomething();
    }
}