使用$this->;有什么区别;somevariable和somevariable,同时使用将新创建的对象存储在ph


What is the difference bw using $this->somevariable and somevariable while using to store a newly created object in php

有人能解释一下以下两个用php编写的代码片段的区别吗?一个使用$this->任务,另一个简单地使用$tasks来存储对象。

 class Foo
{
public $tasks;
function doStuff()
{
    $this->tasks = new Tasks();
    $this->tasks->test();
}
}

class Foo
{
public $tasks;
function doStuff()
{
    $tasks = new Tasks();
    $tasks->test();
}
}

不使用$this时,您使用的是一个局部变量,该变量将在函数doStuff完成时消失。当您使用$this时,当类Foo的实例消失时,该变量将消失。

方法1

$foo = new Foo();
$foo->doStuff();
echo $foo->tasks  --  tasks will be a new instance of Tasks

方法2

$foo = new Foo();
$foo->doStuff();
echo $foo->tasks  --  tasks will be NULL

第一个使Tasks对象成为类Foo的属性。您可以在函数之外访问它。

http://php.net/manual/en/language.oop5.properties.php

在第二个例子中,您将创建一个变量来保存对象,并且它的作用域只是类的方法。在方法之外无法访问它。

http://php.net/manual/en/language.variables.scope.php

如果要从类外的Foo访问Tasks,请使用this。否则只能在doStuff()中访问。

在第二个代码段中,$tasks变量在其他函数中不应该是可访问的,因为您没有设置对象属性,只是设置了一个局部变量。

在第一个中使用类变量$tasks,但在第二个中创建了一个新变量,该变量是函数doStuff()的本地变量

如果不在PHP中使用$this关键字,就无法访问类变量。

使用纯变量名意味着它是该函数的本地变量,而不像Java等其他编程语言,如果在当前作用域中找不到变量名,它会尝试外部作用域。