【问题标题】:this keyword in Java and in PHPJava 和 PHP 中的 this 关键字
【发布时间】:2011-05-20 05:34:15
【问题描述】:

今天我开始开发一个小型 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 php oop this


【解决方案1】:

在 Java 中,您并不总是需要说“这个”,Java 会弄清楚的。唯一需要说 this 的情况是当局部变量与实例变量同名时,在这种情况下,如果你不说 this.var,Java 将使用局部变量

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

【讨论】:

  • 为了清楚起见,我总是包含 this 关键字。事实上,如果我没有包含它,我更愿意编译器生成错误。代码应该清晰。
【解决方案2】:

Java 和 PHP 处理 this 关键字的方式不同。

Read this question and answer,它解释了 PHP 中 this 关键字的一些奇怪行为。

【讨论】:

    【解决方案3】:

    是的,php中的“this”关键字与java中的关键字相同,没有其他区别

    【讨论】:

    • 除了,如果我有属性ab,那么我可以很容易地避免在构造函数中使用this,并在没有this 的情况下分配a = xb = y。不能对 PHP 说同样的话。
    • 在 PHP 中,无论如何都不能省略关键字 $this。在我看来,你也不应该在 java 中省略它。
    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    相关资源
    最近更新 更多