首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >$this->var或$var

$this->var或$var
EN

Stack Overflow用户
提问于 2011-06-17 17:37:46
回答 7查看 3.4K关注 0票数 1

我刚开始使用OOP / CodeIgniter。我想把表单输入赋值给变量。我想知道我应该使用$this -> var还是$var,它们之间有什么不同?谢谢。

例如

代码语言:javascript
复制
$agree = $this -> input -> post( 'agree' );

代码语言:javascript
复制
$this -> agree = $this -> input -> post( 'agree' );

两者都可以很好地工作,如下所示:

代码语言:javascript
复制
if ($agree) { }

代码语言:javascript
复制
if ($this -> agree){ }

谢谢

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-06-17 17:47:30

这是一个范围问题

代码语言:javascript
复制
<?php
    class Example extends CI_Controller
    {
        private $agree1;

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

        public function index()
        {
            $agree2 = $this->input->post( 'agree' );
            $this->agree1 = $this->input->post( 'agree' );

            // within this context both are accessable
            // these will print the same
            var_dump($agree2);
            var_dump($this->agree1);

            // call the helper function
            $this->helper();
        }

        private function helper()
        {
            // within this context $agree2 is not defined
            // these will NOT print the same. Only the 2nd will print the content of the post
            var_dump($agree2);
            var_dump($this->agree1);
        }
    }
?>
票数 2
EN

Stack Overflow用户

发布于 2011-06-17 17:41:47

当涉及到额外的局部变量时,这实际上是一个偏好问题。作为一般指导,如果变量只与方法相关,我将使用$var;如果其他方法也使用此变量,我将使用$this->var

如果您只是收集输入并在该方法中处理它,那么我将只使用一个局部变量。类成员通常用于与类/对象相关的事情,例如,表示车辆的类可能具有$number_of_wheels变量。

票数 2
EN

Stack Overflow用户

发布于 2011-06-17 17:42:24

我假设您讨论的是在控制器/操作对中使用什么?

$this->var实际上引用了一个名为var的控制器类的属性。

$var表示它是一个局部(函数)作用域变量

如果您不是特别想访问某个类属性,请不要使用$this。只需使用$var并使其只能在函数范围内访问即可。

如果您实际引用的是类属性,并且希望类中的所有方法都可以访问此属性,请确保在顶部的类定义中声明它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6383915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档