【问题标题】:Edit protected member in php在 php 中编辑受保护的成员
【发布时间】:2011-01-15 00:50:50
【问题描述】:

我有类似下面的代码:

class ModuleRaceRegistration extends Module
{
    protected $strTemplate = "template";
    protected function compile()
    {
         // this doesn't work
         $this->strTemplate = "template2";
    }
}

compile 函数中,我需要更改$strTemplate 成员。我该怎么做?

【问题讨论】:

  • 为什么这不起作用?如果没有,我想不出一个场景。
  • 我不知道。我可以echo $this->strTemplate; 并且它会回显“template2”,但不会加载 template2 模块(这是 Contao CMS 中的一个模块)。
  • 想通了。事实证明这是 Contao CMS 的竞争条件。您可以投票关闭。 :-)

标签: php protected


【解决方案1】:

是否返回错误?此外,情况可能并非如此,但compileprotected 方法,因此您只能从类中调用它。如果您尝试从课堂外调用它,那么它需要是public

【讨论】:

  • 没有错误。我可以回显 $this->strTemplate;它回显“template2”,但不会加载 template2 模块(这是 Contao CMS 中的一个模块)。 compile 确实被调用并且 template 被加载。
  • 以后会不会在其他地方重新设置为“模板”?出于兴趣,您如何检查是否调用了 compile?
【解决方案2】:

让我试试

来自manual的示例

<?php
abstract class Base {
    abstract protected function _test();
}

class Bar extends Base {

    protected function _test() { }

    public function TestFoo() {
        $c = new Foo();
        $c->_test();
    }
}

class Foo extends Base {
    protected function _test() {
        echo 'Foo';
    }
}

$bar = new Bar();
$bar->TestFoo(); // result: Foo
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2016-06-12
    • 2014-06-09
    • 1970-01-01
    相关资源
    最近更新 更多