我有一个主类:具有构造器的“ 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();
}
}