【问题标题】:Prevent invocation of instance method X from context != Y防止从上下文调用实例方法 X != Y
【发布时间】:2010-04-08 15:00:57
【问题描述】:

这是一个棘手的问题。

我正在“模仿”ZF Bootstrapping(表面外观)。不要问我为什么,称之为学术兴趣。因此,我有一个带有“run”方法的 Bootstrap Abstract,该方法会对其自身进行迭代以定位任何以“init”为前缀的方法。

应用程序会寻找扩展此类的用户定义类,用户可以通过这种方式在其中定义任意数量的方法。但是,我想防止用户能够执行其父类的“运行”命令,同时仍然为客户端代码公开相同的命令。

class Bootstrap_Abstract{
    protected final function run(){
    // if method exists that starts 'init' - execute the method
    }

}

class Bootstrap extends Bootstrap_Abstract(){
    public function initSomething(){
    //do something
    }

    //PREVENT THIS
    public function initRun(){
        $this->run();
    }

}

//application code, not exposed to user - changes in behaviour require changes in this code directly
 class Application(){
     $Bootstrap = new Bootstrap();//load user bootstrap
     $Bootstrap->run();
 }

【问题讨论】:

  • 你能否详细解释一下这句话:“我想阻止用户能够执行其父类的“运行”命令,同时仍然为客户端代码公开相同的命令” ?我不太明白。

标签: php scope visibility


【解决方案1】:

要确定“什么”称为特定方法,请查看 debug_backtrace

【讨论】:

  • OP 举例说明了the XY Problem。虽然这在技术上是问题的答案,但它并不是真正解决 OP 问题的正确方法。
【解决方案2】:

后期脚本: 我的原始代码的问题是设计错误。遍历 Bootstrap 方法的责任应该交给调用类,而不是目标类本身。 我通过将函数移到调用者来解决了这个问题。有趣的是,事后看来重构是多么明显/简单......

【讨论】:

    猜你喜欢
    • 2016-08-30
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多