dongwh1992 2010-12-04 14:29
浏览 71
已采纳

Java和PHP中的这个关键字

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.

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

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 . "
";
        echo "y = " . $this->y . "
";
    }
}

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?

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;

  • 写回答

3条回答 默认 最新

  • dongzhunqiu4841 2010-12-04 15:16
    关注

    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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加