Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
$this在PHP中是什么意思?_Php_Oop_This_Keyword - Fatal编程技术网

$this在PHP中是什么意思?

$this在PHP中是什么意思?,php,oop,this,keyword,Php,Oop,This,Keyword,可能重复: 你好,, 您能帮助我理解PHP变量名$this的含义吗 感谢您的帮助。$此指您所在的班级 比如说 Class Car { function test() { return "Test function called"; } function another_test() { echo $this->test(); // This will echo "Test function called"; } } 希

可能重复:

你好,, 您能帮助我理解PHP变量名
$this
的含义吗


感谢您的帮助。

$此
指您所在的班级

比如说

Class Car {

    function test() {
        return "Test function called";
    }

    function another_test() {
        echo $this->test(); // This will echo "Test function called";
    }
}

希望这能有所帮助。

您可能想看看中的答案


基本上,
$this
指的是当前对象。

$this
是对象中使用的受保护变量,
$this
允许您在内部访问类文件

范例

Class Xela
{
   var age; //Point 1

   public function __construct($age)
   {
      $this->setAge($age); //setAge is called by $this internally so the private method will be run
   }

   private function setAge($age)
   {
      $this->age = $age; //$this->age is the variable set at point 1
   }
}
这基本上是一个变量作用域问题,
$this
仅允许在已启动的对象中使用,并且仅引用该对象及其父对象,您可以在不能超出作用域的位置运行私有方法并设置私有变量

另外,
self
关键字非常相似,除了它指的是类内的静态方法外,static基本上意味着你不能使用
$this
,因为它还不是对象,你必须使用
self::setAge()
如果该
setAge
方法被声明为静态,则不能从该对象的瞬间调用它

一些供您开始使用的链接:


可能的重复项:。另外,在提问时请不要太可爱祝贺你在12岁时扩展了自己的知识!但是,既然这与问题无关,你能编辑问题以删除它吗?堆栈溢出上的人似乎不知道“我12岁了,这是什么”指的是什么。这怎么是一个骗局,他不是在比较
self
$this
的用法,而是想知道
$this
的意思。这是一种引用自身的方式。。。实际上,self指的是您所在的当前类$这是指您所处类的当前对象实例。它不会
回显名为“
的测试函数,因为您正在访问
Test
成员变量(该变量不存在),而不是方法
Test()
。您需要将其更改为
echo$this->test()
…它实际上不是类,而是对象-一个类的实例。实际上它是该类的实例,其中as
self
将静态引用该类,而
\uuuuu CLASS\uuuuu
将类名称为字符串:-)虽然我理解您是在向OOP新手解释,但请不要将对象称为类$这用于引用对象属性和方法,而self::用于引用类属性和方法。我认为解释两者之间的区别很重要。