【发布时间】: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;
【问题讨论】:
-
所以我看到它与 PHP
this关键字的用法有很大不同。还是说语法更好?