Home>Article>Backend Development> Java and PHP overloading comparison case

Java and PHP overloading comparison case

小云云
小云云 Original
2017-11-08 13:35:19 1187browse

We know that PHP is a weakly typed language and does not have overloading like a strongly typed language like JAVA. From this definition, PHP is not overloaded because PHP does not allow the same function name to exist.

But not having it doesn’t mean it can’t be achieved.

1. First, let us take a look at an overloading example in Java:

class demo { public static void main (String[] args) { sum(1,1);//2 sum(1,1.5);//2.5 sum(1.5,1.5);//3.0 } public static void sum(int var1,int var2){ System.out.println(var1+var2); } public static void sum(int var1,double var2){ System.out.println(var1+var2); } public static void sum(double var1,double var2){ System.out.println(var1+var2); } }

What if we use PHP to implement the above example?

2. Optional parameters, allowing variables to set default values

JAVA overloading example:

class demo { public static void main (String[] args) { sum(1,2);//3 sum(1,2,3);//6 } public static void sum(int var1,int var2){ System.out.println(var1+var2); } public static void sum(int var1,int var2,int var3){ System.out.println(var1+var2+var3); } }

Use PHP optional parameter feature to implement:

You can see the same function, but it is simpler to implement in a weakly typed language like php


The above is the detailed content of Java and PHP overloading comparison case. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn