You need to enable JavaScript to run this app. CodeIgniter框架中如何在函数外部访问内部定义的变量值
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter框架中如何在函数外部访问内部定义的变量值

PHP函数内部数据库查询结果外部获取方案

方案1:直接返回变量(最常用,适合单次调用取值)

你只需要在函数末尾添加return语句返回目标变量即可,修正后的函数代码如下:

public function getemailData()
{
    $email_id_investors = $this->db
        ->select('value')
        ->get_where('common_email_settings', ['name' => 'investors_email'])
        ->row()->value;
    // 新增返回语句
    return $email_id_investors;
}

外部调用方式:

// 实例化对应类后直接调用方法即可拿到值
$obj = new 你的类名();
$investorEmail = $obj->getemailData();
// 后续可直接使用$investorEmail变量

方案2:存储为类属性(适合类内多方法复用)

如果你需要在同一个类的多个方法中使用该查询结果,可以把值存到类属性中:

class 你的类名
{
    // 定义类属性,可根据访问范围设置public/protected/private
    public $emailIdInvestors;

    public function getemailData()
    {
        $this->emailIdInvestors = $this->db
            ->select('value')
            ->get_where('common_email_settings', ['name' => 'investors_email'])
            ->row()->value;
    }

    // 类内其他方法可直接调用属性取值
    public function otherMethod()
    {
        echo $this->emailIdInvestors;
    }
}

外部访问方式:

$obj = new 你的类名();
$obj->getemailData(); // 先执行查询赋值
$investorEmail = $obj->emailIdInvestors; // 直接读取属性

注意:原代码中get_where的条件值investors_email没有加引号,PHP会优先识别为常量,若未定义对应常量会抛出警告,建议补充引号避免报错。

内容的提问来源于stack exchange,提问作者NCP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 00:06:08