gpt4 book ai didi

java - Java 和 PHP 中的 this 关键字

转载 作者:行者123 更新时间:2023-11-30 05:58:26 25 4
gpt4 key购买 nike

今天我开始开发一个小型 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 的情况是局部变量与实例变量同名,在这种情况下,如果不说 this.var,Java 将使用局部变量

但如果 this.var 能让您更好地理解代码,即使在 Java 中没有必要,您仍然可以使用它。

关于java - Java 和 PHP 中的 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4353970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com