PHP扩展类和兄弟访问

时间:2012-06-06 21:58:30

标签: php class extends siblings

好吧,所以我想弄清楚如何最有效地构建我的代码。我最近将它从一个带有我所有方法的巨型类文件切换到与一个基类组合的更小的文件。这就是我想要的,但是我无法让它正常工作,我需要一些结构方面的帮助。

基本上我需要这样做:

  • 有些函数只是其他类的“工具”(例如转换器函数等) - 它们需要所有子类都可以访问。
  • 在某些情况下,“儿童一级”需要使用“二级儿童”中的功能。
  • 子类需要能够设置另一个子类可以看到的变量。

请告诉我如何开始这些要求;代码示例将不胜感激!

也许一些伪代码会有所帮助 - 但如果我关闭,请告诉我哪些更好用!

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

到目前为止,我尝试过的东西不起作用......请帮忙!谢谢。

1 个答案:

答案 0 :(得分: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();
    }
}

我确信这并不能完全解决所有问题,但我尽力了。 也许你可以进一步提出你的意图