你什么时候在PHP中使用$ this关键字?

Imr*_*ran 8 php oop

$this什么时候在PHP中使用关键字?据我所知,$this是指在不知道对象名称的情况下创建的对象.

关键字$this也只能在方法中使用?

一个例子可以很好地展示何时可以使用$this.

Gre*_*reg 6

类可以包含自己的常量,变量(称为"属性")和函数(称为"方法").

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

$ 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)

上面的例子将输出:

  • $这是定义的(A)
  • $这个没有定义.
  • $这是定义的(B)
  • $这个没有定义.