this keyword in Java and in PHP

2019-04-14 20:40发布

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;

标签: java php oop this
3条回答
萌系小妹纸
2楼-- · 2019-04-14 20:46

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.

查看更多
乱世女痞
3楼-- · 2019-04-14 20:47

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.

查看更多
仙女界的扛把子
4楼-- · 2019-04-14 20:56

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

查看更多
登录 后发表回答