【问题标题】:Global variables not updating in PHP Codeigniter全局变量未在 PHP Codeigniter 中更新
【发布时间】:2016-10-09 21:49:50
【问题描述】:

我想在我的 MVC 应用程序中更新一个全局变量。我正在通过我的全局变量$foo 传递信息,但由于某种原因,它没有更新class 中的functions 之一中的数据

如何在我的函数中更新$foo 的值?

我的代码:

class example extends CI_Controller {

    private $foo;

    public function __construct() {
        parent::__construct();
        $this->foo = 10;
    }

    public function index() {
        // some code here
        $this->foo = 20;
        $data['main_content'] = 'login_form';
        $this->load->view('includes/template', $data);
    }

    if($this->input->post()) {
       error_log($this->foo);
    }
} 

即使我尝试将值更新为 20,它仍在返回 10

【问题讨论】:

  • 您的问题是设置还是在配置文件或配置项中分配此变量?这样做您可以在所有控制器、模块、视图中轻松访问它
  • 我计划将foo 设置为等于index() 函数@Franco 内的另一个变量
  • 您的代码中没有全局变量。
  • 无论你想在哪里做这件事都没有关系。我想说的是,如果您使用配置项代替此全局变量,则可以轻松操作它,并且可以在任何地方使用它。
  • if($this->input->post()) 代码移动到index() 方法中,这样您就可以真正看到正确的输出。正如@zerkms 所说,$foo 不是全局变量,而是类属性。

标签: php function codeigniter model-view-controller global-variables


【解决方案1】:

我不确定你在这里做什么……但这行得通。

class Main extends CI_Controller {

    private $foo;

    public function __construct() {
        parent::__construct();
        $this->foo = 10;
    }

    public function index() {
        // some code here
        $this->foo = 20;
        echo $this->foo; // The result is 20 as set.
    }
    // hard coded the setter var name for demonstration purposes only
    public function set_foo($foo){
       $this->foo = $foo;
    }
    // hard coded the getter var name for demonstration purposes only
    public function get_foo(){
       return $this->foo;
    }

}

$foo 是类的“属性”,它的所有成员“方法”都可以访问。它不是您所指的全球。 GLOBALS 可供任何事物访问。

【讨论】:

  • 我的问题是它在 index() 函数内回显 20,但不在它之外……所以在我的 ($this->input->post()) 中……它回显了 10
  • 我已经更新了我的答案,说明您将如何访问您的名为 foo 的私有属性...我已经使用 _foo 对函数名称进行了硬编码,只是为了演示该概念。当您需要受保护的数据时,您可以控制如何访问它以防止外部力量更改您的值,如果 foo 设置为 public 可能会出现这种情况......您可能想去阅读有关类的内容以帮助您更好地理解这一点.
  • 如果我在 if 语句中调用 setter,它会起作用,但如果我在 index() 函数中调用它,它就不起作用。我开始思考我的 index() 函数中是否有什么东西阻止了这一切
  • 你能澄清一下你真正想要在这里实现的目标吗?我没有遵循你认为你在做什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多