在 CodeIgniter 控制器中传递函数计算值

霞舞
发布: 2025-08-27 23:13:01
原创
911人浏览过

在 codeigniter 控制器中传递函数计算值

在 CodeIgniter 控制器中,如何在不同的函数之间传递计算后的变量值。重点讲解了通过控制器类的属性以及函数参数传递数据的方法,并提供了代码示例,帮助开发者理解如何在控制器内部共享数据,避免使用 Session 或 Cookie 等方式。

在 CodeIgniter 框架中,经常需要在同一个控制器内的不同函数之间共享数据。例如,一个函数计算得到一个值,需要在另一个函数中使用。本文将介绍几种在 CodeIgniter 控制器中传递变量的方法,并提供示例代码。

方法一:使用控制器类的属性

最常用的方法是将变量定义为控制器的属性。这样,控制器内的所有函数都可以通过 $this-youjiankuohaophpcn属性名 访问该变量。

<?php
class Employees extends CI_Controller {

    private $jwtoken; // 定义控制器属性

    public function __construct() {
        parent::__construct();
    }

    public function auth() {
        $adminEmail = $this->input->post('adminEmail');
        $adminPassword =  $this->input->post('adminPassword');
        if ($adminEmail != "" && $adminPassword != "") {
            $query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
            //if user exist
            if ($query->num_rows() <= 0) {
                $response = array();
                $this->jwtoken = ""; // 初始化控制器属性
                $this->session->set_flashdata("invalid", "Wrong email or password");
                $response = array(
                    'status' => 'invalid',
                    'message' => $_SESSION['invalid'],
                    'token' => $this->jwtoken,
                );
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $this->jwtoken;  //return value
            } else {
                //  $this->session->set_userdata('adminEmail', $adminEmail);
                $response = array();
                $jwt = new JWT();
                $data = array(
                    'adminEmail' => $adminEmail,
                    'iat' => time()
                );
                $this->jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256'); // 设置控制器属性
                // I want to pass $jwtoken's variable to all the functions in a controller

                $this->session->set_flashdata("login", "Scucessfully login!");
                //  if (isset($_SESSION['adminEmail'])) {
                if ($this->jwtoken != "") {
                    $response = array(
                        'status' => 'valid',
                        'message' => $_SESSION['login'],
                        'token' => $this->jwtoken
                    );
                }
                $abc = $this->jwtoken;
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $this->jwtoken; //return value
            }
        }
    }

    public function addNew() {
        $response = array();
        echo $this->jwtoken; // 访问控制器属性
    }
}
?>
登录后复制

说明:

  1. 在 Employees 类中,我们首先定义了一个私有属性 $jwtoken。
  2. 在 auth() 函数中,我们计算得到 $jwtoken 的值,并将其赋值给 $this->jwtoken。
  3. 在 addNew() 函数中,我们通过 $this->jwtoken 访问了 $jwtoken 的值。

优点:

  • 简单易懂,易于实现。
  • 可以在控制器内的任何函数中使用。

缺点:

算家云
算家云

高效、便捷的人工智能算力服务平台

算家云 37
查看详情 算家云
  • 如果控制器属性过多,可能会导致代码难以维护。
  • 所有函数都可以修改该属性,可能导致数据混乱。

方法二:通过函数参数传递

另一种方法是将变量作为参数传递给需要使用它的函数。

<?php
class Employees extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function auth() {
        $adminEmail = $this->input->post('adminEmail');
        $adminPassword =  $this->input->post('adminPassword');
        if ($adminEmail != "" && $adminPassword != "") {
            $query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
            //if user exist
            if ($query->num_rows() <= 0) {
                $response = array();
                $jwtoken = "";
                $this->session->set_flashdata("invalid", "Wrong email or password");
                $response = array(
                    'status' => 'invalid',
                    'message' => $_SESSION['invalid'],
                    'token' => $jwtoken,
                );
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken;  //return value
            } else {
                //  $this->session->set_userdata('adminEmail', $adminEmail);
                $response = array();
                $jwt = new JWT();
                $data = array(
                    'adminEmail' => $adminEmail,
                    'iat' => time()
                );
                $jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
                // I want to pass $jwtoken's variable to all the functions in a controller

                // this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
                $this->addNew($jwtoken);
                // What is the addNew() supposed to do?

                $this->session->set_flashdata("login", "Scucessfully login!");
                //  if (isset($_SESSION['adminEmail'])) {
                if ($jwtoken != "") {
                    $response = array(
                        'status' => 'valid',
                        'message' => $_SESSION['login'],
                        'token' => $jwtoken
                    );
                }
                $abc = $jwtoken;
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken; //return value
            }
        }
    }

    public function addNew($jwtoken = "default_value_if_not_set") {
        echo $jwtoken;
    }
}
?>
登录后复制

说明:

  1. 在 auth() 函数中,我们计算得到 $jwtoken 的值。
  2. 我们调用 addNew() 函数,并将 $jwtoken 作为参数传递给它。
  3. 在 addNew() 函数中,我们接收 $jwtoken 参数,并使用它。

优点:

  • 可以明确指定哪些函数可以使用该变量。
  • 避免了全局变量可能导致的问题。

缺点:

  • 如果需要传递的变量很多,可能会导致函数签名过长。
  • 需要在每次调用函数时都传递参数,比较繁琐。

总结

在 CodeIgniter 控制器中传递变量,可以使用控制器类的属性或函数参数传递。选择哪种方法取决于具体的应用场景。如果需要在多个函数中使用同一个变量,并且不希望频繁传递参数,则可以使用控制器类的属性。如果只需要在特定的函数中使用该变量,并且希望明确指定哪些函数可以使用该变量,则可以使用函数参数传递。

以上就是在 CodeIgniter 控制器中传递函数计算值的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号