我有一个主类:“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();
}
}
关于PHP 类树,其中父类包含子类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7882602/