2014-11-14 53 views
1

我正在开发一个PHP应用程序。我试图找出使用$ this->和为什么总是首选。

我的意思是,我们可以使用此代码

<?php 
class place{ 
    public $country; 
    public function countryName($country){ 
     echo $country; 
    } 
} 
$info = new place(); 
$info->countryName("Nepal"); 
?> 

简单地echo的方法中的属性值,但是,在例子我看到这 - $>以这种方式使用:

<?php 
class place{ 
    public $country; 
    public function countryName($country){ 
     $this->country = $country; 
     echo $this->country; 
    } 
} 
$info = new place(); 
$info->countryName("Nepal"); 
?> 

是使用$ this->首选还是第一种方法完全正常?

+1

'this'不是排他性的OOP – 2014-11-14 17:30:04

+0

的第一种方法是不附和任何性质的境界到PHP ...你不能比较两个代码。 – 2014-11-14 17:30:27

+1

@JayBlanchard,PHP处理'this'与其他语言比如Java和C#不同。 http://stackoverflow.com/questions/4353970/this-keyword-in-java-and-in-php – 2014-11-14 17:41:23

回答

4

$this正在引用当前对象。

作为每php.net

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

2

$this->country会回显你的班级$country,而只有echo $country会回显你的方法级别$country。这完全是因为PHP中的对象是如何工作的以及变量的范围。当你继续寻找,你会看到使用这个有很多更

2

第一电弧不呼应的属性,它只是呼应了在传递的值。

第二消分配的价值传递到物业,然后你用$ this-> country来回应物业。

如果你在第一个弧中回显$ this-> country,你将不会得到任何回显。

1
$this-> 

帮助您参考您的类变量。

例如:

public function countryName($country){ 
     $this->country = $country; 
     echo $this->country; 
    } 

$this->country指的是类var和它的需要设置为参数$country

+0

“帮助你[...]”“你可以在没有它的情况下编码”? – 2014-11-14 17:34:08

+0

对不起,这似乎是我错了。你可以在Java和其他OOP中没有它的代码,但它看起来像在PHP中,你需要使用'$ this' http://stackoverflow.com/questions/4353970/this-keyword-in-java-and-in-php – 2014-11-14 17:38:58

2

$this代表该类的任何实例。所以,当你创建一个对象$USA并调用,$this将代表对象$USA

<?php 
$USA = new place(); 
$USA->countryName("USA"); 
?> 

在代码中,你是呼应功能而不是类属性的参数,但在这里:

<?php 
class place{ 
    public $country;//This is the class attribute. 
    public function countryName($country){ 
     $this->country = $country;/*here you are storing the value of the parameter passed to the function into the class attribute ($this->country)*/ 
     echo $this->country; 
    } 
} 
?> 
3
$this->country 

是相对于类

$country 
国家

是相对于方法

相关问题