今天,我开始研究一个小型Java应用程序。我对PHP OOP有一些经验,并且大多数原理是相同的。尽管我认为,它应该同时适用于两种方式。
但例如,据我了解,关键字this
的使用方式有所不同。
在Java中
class Params
{
public int x;
public int y;
public Params( int x, int y )
{
this.x = x;
this.y = y;
}
public void display()
{
System.out.println( "x = " + x );
System.out.println( "y = " + y );
}
}
public class Main
{
public static void main( String[] args )
{
Params param = new Params( 4, 5 );
param.display();
}
}
同时在PHP中需要做同样的事情
<?php
class Params
{
public $x;
public $y;
public function __construct( $x, $y )
{
$this->x = $x;
$this->y = $y;
}
public void display()
{
echo "x = " . $this->x . "\n";
echo "y = " . $this->y . "\n";
}
}
class Main
{
public function __construct()
{
$param = new Params( 4, 5 );
$param->display();
}
}
$main = new Main();
?>
我只想问
this
关键字是否还有其他区别?如我所见,在Java中,它用于返回已修改对象的实例,并且如果我传递具有相同名称的参数作为类中的属性。然后,要分配值,我需要清楚地显示什么是参数和什么是类属性。例如上图所示:
this.x = x;
最佳答案
在Java中,您不必总是说“此”,Java会弄清楚这一点。您唯一需要说的是本地变量与实例变量同名,在这种情况下,如果您不说this.var,Java将使用本地变量。
但是即使您不需要Java,即使您可以更好地理解代码,也可以说this.var。
关于java - Java和PHP中的此关键字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4353970/