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)?

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

1 个解决方案

#1


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.

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

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.

但是如果你问我 - 我认为你应该考虑你的设计,因为解决方案似乎有点hacky并且很难理解看到代码的人。

更多相关文章

  1. php对象的实现
  2. PHP:将simpleXML对象转换为二维数组
  3. 如何对继承对象进行单元测试?
  4. PHP中类和对象的相关函数
  5. 【PHP面向对象(OOP)编程入门教程】15.static和const关键字的使用
  6. PHP XAMPP配置PHP环境和Apache80端口被占用解决方案
  7. PHP面向对象笔记 —— 113 封装概念
  8. PHP的语言特性-面向对象和C++/java/python的相似之处
  9. php面向对象之抽象类和接口理解

随机推荐

  1. JavaScript中可见性检查的测试条件
  2. EasyUI-datagrid表格(基本使用)
  3. bootstrap入门【按钮式下拉菜单,输入框组
  4. JavaScript 函数柯里化(参考《JavaScript
  5. 如何在WKWebview上监控请求?
  6. bootstrap弹出框的实现
  7. 在AngularJS中轻松控制dom - 单击按钮,然
  8. 【JavaScript 5—基础知识点】:正则表达式
  9. swiper 定位到指定页面或位置
  10. Redux-saga停留在收益率调用上