我刚开始使用OOP / CodeIgniter。我想把表单输入赋值给变量。我想知道我应该使用$this -> var还是$var,它们之间有什么不同?谢谢。
例如
$agree = $this -> input -> post( 'agree' );或
$this -> agree = $this -> input -> post( 'agree' );两者都可以很好地工作,如下所示:
if ($agree) { }或
if ($this -> agree){ }谢谢
发布于 2011-06-17 17:47:30
这是一个范围问题
<?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);
}
}
?>发布于 2011-06-17 17:41:47
当涉及到额外的局部变量时,这实际上是一个偏好问题。作为一般指导,如果变量只与方法相关,我将使用$var;如果其他方法也使用此变量,我将使用$this->var。
如果您只是收集输入并在该方法中处理它,那么我将只使用一个局部变量。类成员通常用于与类/对象相关的事情,例如,表示车辆的类可能具有$number_of_wheels变量。
发布于 2011-06-17 17:42:24
我假设您讨论的是在控制器/操作对中使用什么?
$this->var实际上引用了一个名为var的控制器类的属性。
$var表示它是一个局部(函数)作用域变量
如果您不是特别想访问某个类属性,请不要使用$this。只需使用$var并使其只能在函数范围内访问即可。
如果您实际引用的是类属性,并且希望类中的所有方法都可以访问此属性,请确保在顶部的类定义中声明它。
https://stackoverflow.com/questions/6383915
复制相似问题