php - 你能解释一下 Zend 的 Action Controller 是如何操作的吗?

标签 php oop zend-framework inheritance

很抱歉不断重新编辑我的问题,但看起来这是正确提问的唯一方法。

我最初的问题是以下伪代码( Controller 及其父级)无法正常工作:

class Parent {
    var $data = array();
    public function __construct( OtherClass $otherClass ) {
        $this->data = $otherClass->getData(); //contains some => thing
        $this->init($otherClass->getClassName());
    }
    public function init( $className ) {
        new $className; //new Child
    }
    public function __get( $name ) {
        return array_key_exists($name, $this->data) ? $this->data[$name] : null;
    }
}

class Child extends Parent {
    public function __construct() {
        echo $this->some; //won't return 'thing';
    }
}

fireeyedboy帮了我很多(谢谢)并指出 Zend_Controller_Action 正在做我想做的事,但我不明白他们是怎么做到的?


原始问题

我知道这里有一些类似的问题,但我不能转储它们。我也知道我可以逆转整个过程,所以我可以先初始化 Child 然后调用 parent::__construct 但这对我来说似乎是不需要的。在我的案例中,如何轻松访问 Parent 变量?

更新:

让我澄清一点。 Child 是一个任意 Controller 。 Parent 是所有 Controller 的母亲。许多框架都在做同样的事情,但 Controller 可以利用它们的父 Controller 变量、方法或对象,而无需调用 parent::__construct(因此用不必要的参数填充子类构造函数)。我不想重写这些框架中的任何一个,但我想了解它们是如何运作的。

最佳答案

您的子类没有调用父类的构造函数。这是一个修复:

class Child extends Parent {
   public function __construct() {
       parent::__construct();
       echo $this->some;
   }
}

更新:父类的构造函数不会在 PHP 中自动调用。查看documentation :

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

所以你问的事情不会发生。您误解了类结构或它们的运作方式。请注意,PHP 还支持遗留构造函数命名(至少在 5.3.3 之前):如果类中没有 __construct() 方法,PHP 假定构造函数以类命名(即 class Foo { function Foo() {} ) 将 Foo() 方法视为构造函数)。

关于php - 你能解释一下 Zend 的 Action Controller 是如何操作的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5485026/

相关文章:

php - SELECT DISTINCT 与其他列

php - 重置 PDO 中的光标位置

c++ - 存储此指针以在WndProc中使用的最佳方法

java - 如何在不创建子类和/或继承类的情况下从另一个类调用对象的方法?

zend-framework - Zend_Auth 存储如何工作?

PHP Print 在打印开始时在网页中放置虚假字符 ()

PHPUnit:smarty 模板的代码覆盖率

python - 一个类的多个实例被覆盖

zend-framework - Zend 框架 : How to include an OR statement in an SQL fetchAll()

php - 布局和 View 有什么区别?以 Zend_Layout 和 Zend_View 为例