this keyword in Java and in PHP

醉酒当歌 提交于 2020-01-01 18:14:44

问题


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 . "\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?

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;


回答1:


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:


Yes , "this" keyword in php works the same as in java & there is no other difference




回答3:


Java and PHP are different the way they handle the this keyword.

Read this question and answer, and it explains some odd behaviour of the this keyword in PHP.



来源:https://stackoverflow.com/questions/4353970/this-keyword-in-java-and-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!