Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP two methods with the same name

Tags:

methods

php

class

Can I have two methods sharing the same name, but with different arguments?

One would be public static and would take 2 arguments, the other one just public and takes only one argument

example

class product{

  protected
    $product_id;

  public function __construct($product_id){
    $this->product_id = $product_id;
  }

  public static function getPrice($product_id, $currency){
    ...
  }

  public function getPrice($currency){
    ...
  }

}
like image 263
Alex Avatar asked Dec 07 '11 01:12

Alex


People also ask

Can we have two functions with the same name in PHP?

Note: PHP's interpretation of overloading is different than most object-oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

Can you have two functions with the same name in a PHP class Why or why not?

Since PHP is a dynamically typed language, this is not possible.

What is __ call () in PHP?

The __call() method is invoked automatically when a non-existing method or inaccessible method is called. The following shows the syntax of the __call() method: public __call ( string $name , array $arguments ) : mixed. Code language: PHP (php)

What is __ method __ in PHP?

__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that. __FUNCTION__ returns only the name of the function. while as __METHOD__ returns the name of the class alongwith the name of the function.


1 Answers

No. PHP does not support classic overloading. (It does implement something else that is called overloading.)

You can get the same result by using func_get_args() and it's related functions though:

function ech()
{
  $a = func_get_args();
  for( $t=0;$t<count($a); $t++ )
  {
    echo $a[$t];
  }
}
like image 102
EToreo Avatar answered Oct 21 '22 01:10

EToreo