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

到目前为止,我尝试过的方法不起作用...请帮助!谢谢你。

4

1 回答 1

2

第一点:

对于 Helper 类,您可以选择将方法设为静态,因此您不需要实例:

class Helper
{
  public static function usefulMethod()
  {
     // do something useful here
  }
}

现在可以像这样从任何地方访问:

Helper::usefulMethod()

接下来的几点需要进一步解释,我将其作为注释添加到您的伪代码中:

// always start your class names with upper case letter, it's a good convention
class Main
{
    // don't make this private if you want to access from the child classes too
    // private $test;

    // instead make it protected, so all sub classes can derive
    protected $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()
    {
        // $test is now derived from the parent into the sub class
        $this->test = 'child1 here';
    }
}


class Child2 extends Main
{
    public function __construct()
    {
        // this doesn't quite work like expected:
        // echo 'private call: '.$this->test; //i want this to say "private call: child1 here"

        // because this isn't a reference, but think of every class instance
        // as a container which holds its own properties and methods (variables and functions)
        // if you really want to do it like intended then you would need a subclass from main1
        // but that is kind of strange, I don't know exactly what you want to achieve

        // this will print out 'hello' as expected
        parent::randomFunc();
    }
}

我确信这并不能完全回答所有问题,但我已尽力而为。也许你可以进一步提出你的意图

于 2012-06-06T22:15:59.023 回答