【发布时间】:2012-06-06 21:58:29
【问题描述】:
好的,所以我正在尝试找出如何最有效地构建我的代码。我最近将它从一个包含我所有方法的巨型类文件转换为与一个基类组合的更小文件。这是我想要的,但是我无法让它正常工作,我需要一些关于结构的帮助。
基本上我需要这样做:
- 有些函数只是其他类的“工具”(例如转换器函数等) - 它们需要可供所有子类访问。
- 在某些情况下,“子类 1”需要使用“子类 2”中的函数。
- 子类需要能够设置另一个子类可以看到的变量。
请告诉我如何开始满足这些要求;代码示例将不胜感激!
也许一些伪代码会有所帮助 - 但如果我不在,请告诉我什么会更好!
class main {
private $test;
public function __construct() {
//do some stuff
}
public function getTest() {
echo('public call: '.$this->test);
}
private function randomFunc(){
echo('hello');
}
}
class child1 extends main {
public function __construct() {
parent::$test = 'child1 here';
}
}
class child2 extends main {
public function __construct() {
echo('private call: '.parent::$test); //i want this to say "private call: child1 here"
parent::randomFunc();
}
}
$base = new main;
new child1;
new child2;
$base->getTest();
所以我希望结果是:
private call: child1 here
hello
public call: child1 here
到目前为止,我尝试过的方法不起作用...请帮助!谢谢。
【问题讨论】:
-
你是否考虑过使用 Traits - php.net/manual/en/language.oop5.traits.php
标签: php class extends siblings