PHP如何区分继承链中的$ this指针?

时间:2009-06-26 10:20:15

标签: php inheritance

请查看以下代码剪辑

class A
{
  function __get($name)
  {
    if ($name == 'service') {
        return new Proxy($this);
    }
  }

  function render()
  {
    echo 'Rendering A class : ' . $this->service->get('title');
  }

  protected function resourceFile()
  {
    return 'A.res';
  }
}

class B extends A
{
  protected function resourceFile()
  {
    return 'B.res';
  }

  function render()
  {
    parent::render();

    echo 'Rendering B class : ' . $this->service->get('title');
  }
}

class Proxy
{
  private $mSite = null;

  public function __construct($site)
  {
    $this->mSite = $site;
  }

  public function get($key)
  {
     // problem here
  }
}

// in the main script
$obj = new B();
$obj->render();

问题是:在类'Proxy'的方法'get'中,如何通过仅使用$ mSite(对象指针)提取相应的资源文件名(resourceFile返回名称)?

1 个答案:

答案 0 :(得分:3)

怎么样:

public function get($key)
{
    $file = $this->mSite->resourceFile();
}

但这需要A::resourceFile() public ,否则您无法从对象范围外访问该方法 - 这就是为其设计的访问修饰符。

修改

好的 - 现在我想我明白了,你想要实现的目标。以下示例应演示所需的行为:

class A 
{
    private function _method() 
    { 
        return 'A'; 
    }

    public function render() 
    { 
        echo $this->_method(); 
    }
}

class B extends A 
{
    private function _method() 
    {
        return 'B'; 
    }

    public function render() 
    {
        parent::render();
        echo $this->_method();
    }
}

$b = new B();
$b->render(); // outputs AB

但是如果你问我 - 我认为你应该考虑一下你的设计,因为对于那些看到代码的人来说,这个解决方案看起来有些晦涩难懂。