PHP 和 Java 之间有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/411254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the differences between PHP and Java?
提问by Click Upvote
What are the main differences between PHP and Java that someone proficient in PHP but learning Java should know about?
精通 PHP 但学习 Java 的人应该知道 PHP 和 Java 之间的主要区别是什么?
Edit:I mean differences in the syntax of the languages, i.e their data types, how they handle arrays & reference variables, and so forth :)
编辑:我的意思是语言语法的差异,即它们的数据类型,它们如何处理数组和引用变量,等等:)
采纳答案by Alan Storm
Not an exhaustive list, and I'm PHP developer who did a tour of Java a while back so Caveat Emptor.
这不是一个详尽的列表,我是 PHP 开发人员,不久前对 Java 进行了一次巡回演出,所以请注意 Emptor。
Every variable in Java needs to be prepended with a data type. This includes primitive types such as boolean, int, double and char, as well as Object data-types, such as ArrayList, String, and your own objects
Java 中的每个变量都需要在前面加上数据类型。这包括基本类型,例如 boolean、int、double 和 char,以及 Object 数据类型,例如 ArrayList、String 和您自己的对象
int foo = 36;
char bar = 'b';
double baz = 3.14;
String speech = "We hold these truths ...";
MyWidget widget = new MyWidget(foo,bar,baz,speech);
Every variable can only hold a value of its type. Using the above declarations, the following is not valid
每个变量只能保存其类型的值。使用上述声明,以下内容无效
foo = baz
Equality on objects (not on primitive types) checks for object identity. So the following un-intuitively prints false. Strings have an equality method to handle this.
对象上的相等性(不是原始类型)检查对象身份。因此,以下不直观地打印错误。字符串有一个相等的方法来处理这个问题。
//see comments for more information on what happens
//if you use this syntax to declare your strings
//String v1 = "foo";
//String v2 = "foo";
String v1 = new String("foo");
String v2 = new String("foo");
if(v1 == v2){
println("True");
}
else{
println("False");
}
Arrays are your classic C arrays. Can only hold variables of one particular type, need to be created with a fixed length
数组是经典的 C 数组。只能保存一种特定类型的变量,需要以固定长度创建
To get around this, there's a series of collection Objects, one of which is named ArrayList that will act more like PHP arrays (although the holds one type business is still true). You don't get the array like syntax, all manipulation is done through methods
为了解决这个问题,有一系列集合对象,其中一个名为 ArrayList,它的行为更像 PHP 数组(尽管持有一种类型的业务仍然如此)。你不会像语法那样得到数组,所有的操作都是通过方法完成的
//creates an array list of strings
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("My First Item");
ArrayLists still have numeric keys. There's another collection called HashMap that will give you a dictionary (or associative array, if you went to school in the 90s) like object.
ArrayLists 仍然有数字键。还有一个叫做 HashMap 的集合,它会给你一个字典(或关联数组,如果你在 90 年代上过学)像对象。
ArrayLists and other collections are implemented with something called generics (the <String>). I am not a Java programmer, so all I understand about Generics is they describe the type of thing an Object will operate on. There is much more going on there.
ArrayLists 和其他集合是用称为泛型(<String>)的东西实现的。我不是 Java 程序员,所以我对泛型的理解是它们描述了对象将操作的事物的类型。还有更多事情要做。
Java has no pointers. However, all Objects are actually references, similar to PHP 5, dissimilar to PHP 4. I don't thinkJava has the (depreciated) PHP &reference &syntax.
Java 没有指针。但是,所有对象实际上都是引用,类似于 PHP 5,与 PHP 4 不同。我认为Java 没有(贬值的)PHP &reference & 语法。
All method parameters are passed by value in Java. However, since all Objects are actually references, you're passing the value of the reference when you pass an object. This means if you manipulate an object passed into a method, the manipulations will stick. However, if you try something like this, you won't get the result you expect
Java中所有方法参数都是按值传递的。但是,由于所有对象实际上都是引用,因此在传递对象时传递的是引用的值。这意味着如果您操作传递给方法的对象,操作将保持不变。然而,如果你尝试这样的事情,你不会得到你期望的结果
public void swapThatWontWork(String v1, String v2)
{
String temp = var1;
var1 = var2;
var2 = temp;
}
It's as good a time as any to mention that methods need to have their return type specified, and bad things will happen if an method returns something it's not supposed to. The following method returns an int
现在是提及方法需要指定其返回类型的好时机,如果方法返回它不应该返回的东西,那么糟糕的事情就会发生。以下方法返回一个 int
public int fooBarBax(int v1){
}
If a method is going to throw an exception, you have to declare it as such, or the compiler won't have anything to do with it.
如果一个方法要抛出一个异常,你必须这样声明它,否则编译器将与它无关。
public int fooBarBax(int v1) throws SomeException,AnotherException{
...
}
This can get tricky if you're using objects you haven't written in your method that might throw an exception.
如果您使用的对象不是您在方法中编写的可能会引发异常的对象,则这可能会变得棘手。
You main code entry point in Java will be a method to a class, as opposed to PHPs main global entry point
Java 中的主要代码入口点将是类的方法,而不是 PHP 的主要全局入口点
Variable names in Java do not start with a sigil ($), although I think they can if you want them to
Java 中的变量名不以符号 ($) 开头,尽管我认为如果您希望它们可以
Class names in Java are case sensitive.
Java 中的类名区分大小写。
Strings are not mutable in Java, so concatenation can be an expensive operation.
字符串在 Java 中是不可变的,因此连接可能是一项昂贵的操作。
The Java Class library provides a mechanism to implement threads. PHP has no such mechanism.
Java 类库提供了一种实现线程的机制。PHP 没有这样的机制。
PHP methods (and functions) allow you have optional parameters. In java, you need to define a separate method for each possible list of parameters
PHP 方法(和函数)允许您拥有可选参数。在java中,你需要为每个可能的参数列表定义一个单独的方法
public function inPHP($var1, $var2='foo'){}
public void function inJava($var1){
$var2 = "foo";
inJava($var1,$var2);
}
public void function inJava($var1,$var2){
}
PHP requires an explicit $this be used when an object calls its own methods methods. Java (as seen in the above example) does not.
PHP 要求在对象调用其自己的方法时使用显式 $this。Java(如上例所示)没有。
Java programs tend to be built from a "program runs, stays running, processes requests" kind of way, where as PHP applications are built from a "run, handle the request, stop running" kind of way.
Java 程序倾向于以“程序运行、保持运行、处理请求”的方式构建,而 PHP 应用程序则以“运行、处理请求、停止运行”的方式构建。
回答by Lena Schimmel
I think these two languages (as well as their runtime systems) are too different to list all differences. Some really big ones that come to my head:
我认为这两种语言(以及它们的运行时系统)差异太大,无法列出所有差异。我想到了一些非常重要的:
- Java is compiled to bytecode, PHP is interpreted (as Alan Storm pointed out, since PHP 4, it's not, but it still behaves as if it was);
- Java is strong and statically typed, while PHP is rather weakly and dynamically typed;
- PHP is mostly used to dynamically generate Web pages. Java can do that too, but can do anything else as well (like Applets, mobile phone software, Enterprise stuff, desktop applications with and without GUI, 3d games, Google Web Toolkit...); and
- add your favourite difference here
- Java 被编译为字节码,PHP 被解释(正如 Alan Storm 指出的,从 PHP 4 开始,它不是,但它仍然表现得好像它是);
- Java 是强类型和静态类型,而 PHP 是弱类型和动态类型;
- PHP 主要用于动态生成网页。Java 也可以做到这一点,但也可以做其他任何事情(例如 Applet、手机软件、企业内容、带或不带 GUI 的桌面应用程序、3d 游戏、Google Web Toolkit...);和
- 在此处添加您最喜欢的差异
You will notice most differences when it's time to, but what's most important:
您会在需要时注意到大多数差异,但最重要的是:
- PHP offers OOP (object-oriented programming) as an option that is ignored in most projects. Java requires you to program the OOP way, but when learning Java with a background in a not-so-OOP-language, it's really easy to mess things up and use OOP the wrong way (or you might call it the sub-optimum way or the inefficient way...).
- PHP 提供 OOP(面向对象编程)作为在大多数项目中被忽略的选项。Java 要求您以 OOP 方式进行编程,但是在以不那么 OOP 语言的背景学习 Java 时,很容易将事情搞砸并以错误的方式使用 OOP(或者您可以称其为次优方式)或低效的方式......)。
回答by cletus
- Java is strongly-typed. PHP isn't;
- PHP does a lot of implicit type conversion, which can actually be problematic and is why PHP5 has operators like
===
and!==
. Java's implicit type conversion is primarily limited to auto-boxing of primitive types (PHP has no primitive types). This often comes up.
- Java 是强类型的。PHP 不是;
- PHP 做了很多隐式类型转换,这实际上是有问题的,这也是 PHP5 有像
===
and 之类的运算符的原因!==
。Java 的隐式类型转换主要限于原始类型的自动装箱(PHP 没有原始类型)。这经常出现。
Consider:
考虑:
$val = 'a';
if (strpos('abcdefghij', $val)) {
// do stuff
}
which is incorrect and will have the block not executed because the return index of 0
is converted to false
. The correct version is:
这是不正确的,并且不会执行该块,因为 的返回索引0
被转换为false
. 正确的版本是:
$val = 'a';
if (strpos('abcdefghij', $val) !== false) {
// do stuff
}
Java conditional statements require an explicit boolean
;
Java 条件语句需要一个显式的boolean
;
- PHP variables and arrays are all prepended by
$
and otherwise indistinguishable; - The equivalent of PHP associative arrays is PHP
Maps
(egHashMap
). Associative arrays are ordered on insertion order and can be used like ordinary arrays (on the values). Theres oneMap
implementation that maintains insertion order in Java but this is the exception rather than the norm; $arr['foo'] = 'bar'
insert or update an element in an associative array. Java must useMap.put()
andMap.get()
;- PHP5 has the equivalent of function pointers and anonymous functions (using
create_function()
); 5.3 introduces closures at the language level. Java must use inner classes for both, which is somewhat more verbose. Moreover, inner classes are limited in how they can access variables from the outer scope (read Java Closureson JavaPapers), making them not as powerful as true closures. - Variable declaration is optional in PHP;
- Use of global variables within functions requires explicit use of the
global
keyword in PHP; - POST/GET parameters are, unless configured otherwise (
register_globals()
) automatically result in global variables of the same name. They can alternatively be accessed via the$_POST
global variable (and$_SESSION
for session variables) whereas support for these things comes from a JEE add-on called the servlets API via objects likeHttpServletRequest
andHttpSession
; - Function declaration in PHP uses the
function
keyword whereas in Java you declare return types and parameter types; - PHP function names can't normally clash whereas Java allows method overloading as long as the different method signatures aren't ambiguous;
- PHP has default values for function arguments. Java doesn't. In Java this is implemented using method overloading.
- PHP supports the missing-methodpattern, which is confusingly called "overloading" in the PHP docs.
- PHP 变量和数组都在前面加上
$
,否则无法区分; - PHP 关联数组的等价物是 PHP
Maps
(例如HashMap
)。关联数组按插入顺序排序,可以像普通数组一样使用(在值上)。Map
在 Java 中有一种维护插入顺序的实现,但这是例外而不是规范; $arr['foo'] = 'bar'
在关联数组中插入或更新元素。Java 必须使用Map.put()
和Map.get()
;- PHP5 相当于函数指针和匿名函数(使用
create_function()
);5.3 在语言层面引入了闭包。Java 必须对两者都使用内部类,这有点冗长。此外,内部类在如何从外部范围访问变量方面受到限制(阅读JavaPapers 上的Java 闭包),使它们不如真正的闭包强大。 - 变量声明在 PHP 中是可选的;
- 在函数中使用全局变量需要
global
在 PHP 中显式使用关键字; - POST/GET 参数是,除非另外配置 (
register_globals()
) 会自动生成同名的全局变量。它们也可以通过$_POST
全局变量(和$_SESSION
会话变量)访问,而对这些东西的支持来自一个 JEE 附加组件,称为 servlets API,通过像HttpServletRequest
和这样的对象HttpSession
; - PHP 中的函数声明使用
function
关键字,而 Java 中声明返回类型和参数类型; - PHP 函数名通常不会发生冲突,而 Java 允许方法重载,只要不同的方法签名没有歧义;
- PHP 具有函数参数的默认值。Java 没有。在 Java 中,这是使用方法重载来实现的。
- PHP 支持缺失方法模式,它在 PHP 文档中被混淆地称为“重载”。
Compare:
相比:
function do_stuff($name = 'Foo') {
// ...
}
to
到
void doStuff() {
doStuff("Foo");
}
void doStuff(String what) {
// ...
}
- String constants in PHP are declared using single or double quotes, much like Perl. Double quotes will evaluate variables embedded in the text. All Java String constants use double quotes and have no such variable evaluation;
- PHP object method calls use the
->
operator. Java uses the.
operator; - Constructors in Java are named after the class name. In PHP they are called
__construct()
; - In Java objects,
this
is implicit and only used to be explicit about scope and in certain cases with inner classes. In PHP5,$this
is explicit; - Static methods in Java can be called with either the
.
operator on an instance (although this is discouraged it is syntactically valid) but generally the class name is used instead.
- PHP 中的字符串常量使用单引号或双引号声明,很像 Perl。双引号将评估嵌入在文本中的变量。所有 Java 字符串常量都使用双引号并且没有这样的变量评估;
- PHP 对象方法调用使用
->
运算符。Java 使用.
运算符; - Java 中的构造函数以类名命名。在 PHP 中,它们被称为
__construct()
; - 在 Java 对象中,
this
是隐式的,仅用于明确范围,在某些情况下与内部类有关。在 PHP5 中,$this
是显式的; - Java 中的静态方法可以
.
使用实例上的运算符调用(尽管不鼓励这样做,但它在语法上是有效的),但通常使用类名来代替。
These two are equivalent:
这两个是等价的:
float f = 9.35f;
String s1 = String.valueOf(f);
String s2 = "My name is Earl".valueOf(f);
but the former is preferred. PHP uses the ::
scope resolution operator for statics;
但前者是首选。PHP 使用::
作用域解析运算符来处理静态变量;
- Method overriding and overloading is quite natural in Java but a bit of a kludge in PHP;
- PHP code is embedded in what is otherwise largely an HTML document, much like how JSPs work;
- PHP uses the
.
operator to append strings. Java uses+
; - Java 5+ methods must use the ellipsis (
...
) to declare variable length argument lists explicitly. All PHP functions are variable length; - Variable length argument lists are treated as arrays inside method bodies. In PHP you have to use
func_get_args()
,func_get_arg()
and/orfunc_num_args()
; - and no doubt more but thats all that springs to mind for now.
- 方法覆盖和重载在 Java 中很自然,但在 PHP 中有点混乱;
- PHP 代码嵌入在主要是 HTML 文档的内容中,就像 JSP 的工作方式一样;
- PHP 使用
.
运算符来附加字符串。Java 使用+
; - Java 5+ 方法必须使用省略号 (
...
) 显式声明可变长度参数列表。所有 PHP 函数都是可变长度的; - 可变长度参数列表被视为方法体内的数组。在 PHP 中,您必须使用
func_get_args()
,func_get_arg()
和/或func_num_args()
; - 毫无疑问,这就是现在想到的所有内容。
回答by Malx
you could use JavaDoctool to autogenerate documentation on your software. But you need to write comments in specific way.
you can't run PHP on mobile phones :) There are a lot of run time environments and platforms. That means you need to think in advance which libraries there could be missing or which limitations there could be (screen size, memory limits, file path delimiter "/" or "\" e.g).
您可以使用JavaDoc工具自动生成有关您软件的文档。但是您需要以特定方式编写注释。
你不能在手机上运行 PHP :) 有很多运行时环境和平台。这意味着您需要提前考虑可能缺少哪些库或可能存在哪些限制(例如屏幕大小、内存限制、文件路径分隔符“/”或“\”)。