什么是变量独立$this在 CodeIgniter 中的方法中的含义


What is variable stand-alone $this means in a method in CodeIgniter

我对独立变量$this在某些CodeIgniter函数中的实际含义感到困惑。我理解箭头$this,但我不知道如何在函数中使用$this。例如

function update_entry()
{
    $this->title   = $_POST['title'];
    $this->content = $_POST['content'];
    $this->date    = time();
    $this->db->update('entries', $this, array('id' => $_POST['id']));
}

从字面上看,您不能在函数中使用$this

$this 是引用对象或类实例的伪变量

您可以在方法中使用它而不是在函数中使用它。

但是,您的误解是完全合法的,因为在 php 中,方法是通过以下方式声明的...... function关键词!唯一的语法区别是类内的"函数"是方法,而类外的函数是......一个函数。

例:

<?php
    class MyClass
    {
        public $var = 'Hello';
        /* echo() is a MyClass method */
        function echo()
        {
            echo $this->var;                     // <-- $this inside class: valid
        }
    }
    echo $this;                                  // <-- $this outside class: NOT valid
    /* test() is a function */
    function test()
    {
        echo $this;                              // <-- $this inside function: NOT valid
    }
?>

$this引用类的实例,因此,在此示例中:

$obj = new MyClass();
$obj->test();                                    // <-- Output: "Hello"
$obj->var = "Hello World";
$obj->test();                                    // <-- Output: "Hello World"
$obj2 = new MyClass();
$obj2->test();                                   // <-- Output: "Hello"
$obj2->var = "Hello Baby";
$obj2->test();                                   // <-- Output: "Hello Baby"

$this 是对对象 $obj$obj2 的引用,而不是对泛型声明类的引用:要引用当前类而不是对象,您必须使用 self 而不是 $this

换句话说,您必须对非静态成员使用 $this,对静态成员使用 self


  • 查看有关基本类语法的详细信息

编辑:

当"$this"在方法中单独存在时,您仍然感到困惑。

请参阅此示例:

class Called
{
    public $var = 'Hello Baltimora';
    function echo( $obj )
    {
        echo $obj->var;
    }
}
class Caller
{
    public $var = 'Hello San Francisco';
    function echo( $obj )
    {
        $obj->echo( $this );
    }    
}
$called = new Called();
$caller = new Caller();
$caller->echo( $called );

在类Caller中,方法echo $this(对自己的实例的引用)传递给不同的类方法(Called->echo,实例化为$called):在调用的方法中,Caller实例($caller)被分配给$obj变量并用于检索他的$var变量。

因此,$caller->echo( $called )将输出"你好旧金山"。