【问题标题】:Codeigniter driver call parent method in child constructCodeigniter 驱动程序在子构造中调用父方法
【发布时间】:2020-01-02 06:58:59
【问题描述】:

我在 Codeigniter 中实现驱动程序时遇到问题。

我需要访问父类的方法作为子类中的全局变量。

这是我的代码

父类

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Prueba extends CI_Driver_Library  {

    protected $notifica_grupo;

    public function __construct() {
        $this->valid_drivers = array('uno', 'dos');
        $this->notifica_grupo     = "foo";
    }

    public function notifica_grupo() {
        return $this->notifica_grupo;
    }
}

儿童班

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Prueba_uno extends CI_Driver {

    private $ci;
    protected $notifica;

    public function __construct() {
        $this->ci =& get_instance();
        $this->notifica = $this->_parent->notifica_grupo();
    }

    public function test1(){
        echo $this->notifica;
    }

}

调用$this->prueba->uno->test1()时出现以下错误;

    Type: Error

    Message: Call to a member function notifica_grupo() on null

    Filename: /xxx/application/libraries/Prueba/drivers/Prueba_uno.php

    Line Number: 10

    Backtrace:

    File: /xxx/application/controllers/Test.php
    Line: 33
    Function: __get

所以,我的问题是......有没有办法从孩子的构造访问父方法?

更新: 我尝试了不同的想法,没有一个奏效。这些是场景:

  1. 试图直接获取变量而不是从父方法获取:$this-&gt;notifica = $this-&gt;_parent-&gt;notifica_grupo;。结果:
Message: Trying to get property 'notifica_grupo' of non-object
  1. 在 Child 类中将“扩展 CI_Driver”更改为“扩展 Prueba”。结果:
Invalid driver requested: Prueba_uno__parent
  1. 在 Child 类中将“extends CI_Driver”更改为“extends Prueba”,并在子构造函数中将变量值中的“_parent”删除为:$this-&gt;notifica = $this-&gt;notifica_grupo(); 返回此错误:
Message: Call to undefined method Prueba_uno::decorate()
  1. 在子构造函数中添加parent::__construct();,然后尝试从父方法或直接变量中获取值。返回:
Type: Error
Message: Cannot call constructor

【问题讨论】:

  • 你应该写class Prueba_uno extends Prueba 而不是class Prueba_uno extends CI_Driver
  • 嗨@L.Faros 我试过了,但它仍然不起作用。我已经更新了我的问题以显示不同情况下的不同错误。顺便说一句,我使用 CodeIgniter 而不是纯 PHP。

标签: php codeigniter driver


【解决方案1】:

您没有扩展父类。您的子类必须使用父类名称来扩展,即 Prueba。你正在扩展 CI_Driver

您需要为此使用父类,您可以这样做 $this->notifica = Prueba ::notifica_grupo();

希望对你有帮助

【讨论】:

  • 据我了解,CodeIgniter Driver 中的子类必须扩展 CI_Driver 而不是父类。您是否有关于不扩展 CI_Driver 而是扩展父类名称是否有效或良好做法的信息?我已经实现了你指出的更改,扩展了父类,并通过 $this->notifica = Prueba::notifica_grupo(); 调用了方法结果如下错误:Message: Call to undefined method Prueba_uno::decorate()
  • 我认为这可以帮助你stackoverflow.com/questions/23530989/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 2011-03-24
相关资源
最近更新 更多