【发布时间】:2014-10-11 15:48:48
【问题描述】:
为了加深我对 OOP 的理解,我决定使用抽象类重构我的一些代码。思路大致;
- 一个“父”抽象类构成所有子类扩展的基础。
- 一个“助手”类,其中包含抽象类的子类需要的一系列方法。
- “助手”类将被其他类使用,所以我不希望它成为抽象类的一个组成部分。
问题;
子类按预期扩展了抽象类,但 PHP 警告我抽象类的构造函数中缺少 $helper 参数。我相信构造函数被调用是因为我的子类中没有构造函数,这很好,但是由于您不直接调用抽象类,我该如何让它工作?示例代码如下;
abstract class Parent_Abstract
{
public $input_helper_methods;
public function __construct( $helpers = NULL )
{
//set the helper methods
$this->input_helper_methods = $helpers;
}
}
变量$helpers 目前在另一个文件中,该文件包含在抽象类文件的顶部。同样,我认为这是如何完成的问题。当我了解结构后,我想使用自动加载器,但现在,手动就可以了。这是那个文件的内容;
class RD_Form_Input_Helper_Methods
{
private $var = 'something';
}
$helpers = new RD_Form_Input_Helper_Methods;
我希望这是有道理的。感谢您花时间阅读/回复。
另一个例子;
//"helper" classes. I would like these methods to be available to Child_One and Child_Two
class Helper_Functions {}
class Formatting_Functions {}
abstract class Parent_Abstract()
{
private $helper_functions;
private $formatting_functions;
public function __construct( $object_one, object_two )
{
$this->helper_functions = $object_one;
$this->helper_functions = $object_two;
}
}
class Child_One extends Parent_Abstract
{
//I can use any of the properties or methods from the Helper_Functions or Formatting_Function class
}
class Child_Two extends Parent_Abstract
{
//I can use any of the properties or methods from the Helper_Functions or Formatting_Function class
}
【问题讨论】:
-
不。我在下面的答案中看到了您的回复并在那里回复。
标签: php class dependency-injection abstract-class abstract