【问题标题】:How to call a function of a class from another class?如何从另一个类调用一个类的函数?
【发布时间】:2015-11-24 19:11:37
【问题描述】:

我想知道如何调用Appointments 类中可用的index 函数,结构如下:

class Appointments extends CI_Controller 
{
public function __construct() 
{
    parent::__construct();
    $this->load->library('session');

    if ($this->session->userdata('language'))
    {
        $this->config->set_item('language', $this->session->userdata('language'));
        $this->lang->load('translations', $this->session->userdata('language'));
    }
    else
    {
        $this->lang->load('translations', $this->config->item('language'));
    }
}

/**
 * @param string $appointment_hash 
 */

public function index($appointment_hash = '') 
{...

来自另一个名为Backend_api 的类。通常为了调用一个函数,我会加载模型,但在这种情况下,我没有模型,只有一个类。抱歉,如果这个问题很愚蠢,但我是 CodeIgniter 的新手,我没有找到任何可以帮助我的东西。

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    从同一个班级你可以这样调用

    $this->index($appointment_hash);
    

    您可以在 backend_api 中扩展约会类,也不要在 backend_api 控制器中创建函数名称为 index()

    class Backend_api extends Appointments {
    public function __construct() 
    {
        parent::__construct();
        $this->index($appointment_hash);
    
    }
    
    }
    

    【讨论】:

    • 现在的问题是我已经有了一个extends,此时我该如何扩展多个类?
    • 你不能 (php.net/manual/en/keyword.extends.php) 要解决这个问题,你可以按照上面的建议在 Backend_api 中创建一个 Appointments 类的实例。一种更优雅的方法是使用依赖注入:php-di.org/doc/understanding-di.html/code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146
    【解决方案2】:

    这很简单,只要做:

    $this-> index(<parameter>);
    

    我强烈建议您查看 PHP 文档:http://php.net/manual/en/language.oop5.basic.php

    【讨论】:

    • 不,我不在同一个类中,我想从 Backend_api 类调用位于 Appointments 类中的索引函数
    • 抱歉,从您的代码示例来看,您看起来很像在同一个班级,但我没有正确评论您的评论。如果你试图从另一个函数访问一个函数,你总是可以在 Backend_api 中创建一个 Appointments 类的实例......或者让你的 index() 函数成为一个 statis 函数。
    猜你喜欢
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2018-07-30
    • 1970-01-01
    • 2017-08-10
    相关资源
    最近更新 更多