帮助我理解PHP中如何使用这个

dcl*_*901 5 php oop variables this

用简单的英语,如何$this在PHP中使用?

这在JavaScript中对我来说是一个简单的概念,但由于某种原因在PHP中,我无法理解这个变量及其功能.在任何给定的点上,它究竟指的是什么?我只有OOP的三级经验,我怀疑这就是为什么我很难理解它的用法,但我想要变得更好,我检查的很多代码都使用这个变量.

sha*_*mar 16

非常简单的英语:

一旦进入对象的函数,就可以完全访问它的变量,但是要设置它们,你需要比仅使用你想要使用的变量名更具体.要正确指定要使用局部变量,需要使用特殊$this变量,PHP始终将其设置为指向您当前使用的对象.

例如:

function bark()
{
    print "{$this->Name} says Woof!\n";
} 
Run Code Online (Sandbox Code Playgroud)

每当你在一个对象的函数内部时,PHP自动设置$this包含该对象的变量.您无需执行任何操作即可访问它.


在普通英语中:

$this是一个伪变量,在从对象上下文中调用方法时可用.它是对调用对象的引用(通常是方法所属的对象,但如果从辅助对象的上下文静态调用该方法,则可能是另一个对象)

一个例子:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        A::foo();
    }
}

$a = new A();
$a->foo();

// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
Run Code Online (Sandbox Code Playgroud)

输出:

$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.
Run Code Online (Sandbox Code Playgroud)

  • 感谢这个答案的深度和广度.真正的模范SO公民. (2认同)