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
相关产品推荐
相关产品推荐

