什么时候在PHP中使用$ this关键字? [英] When would you use the $this keyword in PHP?

查看:63
本文介绍了什么时候在PHP中使用$ this关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When would you use the $this keyword in PHP? From what I understand $this refers to the object created without knowing the objects name.

关键字$this只能在方法内使用吗?

Also the keyword $this can only be used within a method?

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

An example would be great to show when you can use $this.

推荐答案

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

A class may contain its own constants, variables (called "properties"), and functions (called "methods").

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

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>

$ this伪变量的一些示例:

Some examples of the $this pseudo-variable:

<?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();
?>

上面的示例将输出:

  • $ this已定义(A)
  • $ this未定义.
  • $ this已定义(B)
  • $ this未定义.

这篇关于什么时候在PHP中使用$ this关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆