views:

384

answers:

1

Please look at the following code snipped

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();

Question is: in method 'get' of class 'Proxy', how I extract the corresponding resource file name (resourceFile returns the name) by using only $mSite (object pointer)?

+3  A: 

What about:

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

But this requires A::resourceFile() to be public otherwise you cannot access the method from outside the object scope - that's what access modifiers have been designed for.

EDIT:

OK - now I think I do understand, what you want to achieve. The following example should demonstrate the desired behavior:

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

But if you ask me - I think you should think about your design as the solution seems somewhat hacky and hard to understand for someone looking at the code.

Stefan Gehrig
No if that was that easy, i would not ask it here, I am asking this from others, cause I have in black box, nowhere to go.yes, resourceFile method IS public, that is my fault. Problem is when it is overridable method, and it is always overriden in the derived classes. So when B object's render method is called, it calls the parent classes render method also, so B object calls the Proxy's get method and also, parent object A also calls the Proxy's get method, Proxy class has no way of differentiating between A and B, it always calls B's resourceFile, cause it is overriden!
Joshua
Edited my answer with a possible solution.
Stefan Gehrig