Java and PHP overloading comparison case

小云云
Release: 2023-03-17 08:20:01
Original
1229 people have browsed it

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); } }
Copy after login

What if we use PHP to implement the above example?

<?php function sum($var1,$var2){ echo $var1+$var2; } sum(1,1);//2 sum(1,1.5);//2.5 sum(1.5,1.5);//3 ?>
Copy after login

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);
    }
}
Copy after login

Use PHP optional parameter feature to implement:

<?php function sum($var1,$var2,$var3=NULL){//$var3设置默认值 echo $var1+$var2+$var3; } sum(1,2);//2 sum(1,2,3);//2.5 ?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template