Java和PHP中的这个关键字 [英] this keyword in Java and in PHP

查看:91
本文介绍了Java和PHP中的这个关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我开始研究一个小型Java应用程序。我有一些PHP OOP的经验,大多数原则是一样的。虽然我认为它应该适用于两种方式。

Today I started work on a small Java app. I have some experience with PHP OOP and mostly the principle is one and the same. Though I thought, that it should apply both ways.

但是例如关键字这个的使用方式不同,据我所知。
在Java中

But for instance keyword this is used differently as I understand. In 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中需要制作同样的事情

At the same time in PHP it is needed to make same thing

<?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();

?>

我想问一下中是否存在其他差异这个关键字?

I just would like to ask are there some other differences in this keyword?

因为我看到,在Java中它用于返回修改对象的实例,如果我传递参数具有相同的名称,作为类中的属性。然后分配值我需要清楚地显示什么是参数和什么是类属性。例如,如上所示: this.x = x;

Since I see, that in Java it is used to return instance of modified object and if I pass argument with same name, as atribute in the class. Then to assign value I need to distinctly show what is argument and what is class attribute. For example as shown above: this.x = x;

推荐答案

在Java中,您并不总是需要说'这个'Java会解决它。当你需要说这个时,唯一的情况是局部变量与实例变量的名称相同,在这种情况下,如果你不说this.var

In Java you don't always need to say 'this' Java will figure it out. The only situation when you need to say this is when the local variable is the same name as instance variable, in which case Java will use local variable if you don't say this.var

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

But you still can say this.var even when it's not necessary in Java if it makes you understand the code better.

这篇关于Java和PHP中的这个关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆