A
A
Artem2015-11-03 13:33:42
PHP
Artem, 2015-11-03 13:33:42

How to throw an error when overloading a method?

Hello everyone again.
There is a certain method that takes 2 arguments as input, but if more than 2 arguments are sent to it, it will still continue to work, how to make it so that it would give an error when overloaded, and how to notice this very overload?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Mikhail Osher, 2015-11-03
@miraage

DEMO .

function foo($bar, $baz)
{
  $argsCount = func_num_args();

  if ($argsCount === 2) {
    echo "correct \n";
  } else {
    echo "error: expected 2 arguments, got $argsCount\n";
  }
}

A
Andrew, 2015-11-03
@R0dger

Try to do this - add the third parameter to the method with the default null, and then check in the method if the third parameter is present, then you sent more than 2 ... a crutch, but I hope it helps.

D
Dmitry, 2015-11-03
@mytmid

function func( $var1, $var2, ...$params)
{
  if( !empty($params) ) echo 'Передано больше двух параметров!';
}

func(1,2,3); //вызываем

I don't remember exactly what version of PHP it will work with, mine from PHP 5.6

O
OnYourLips, 2015-11-03
@OnYourLips

There is a method that takes 2 arguments as input, but if more than 2 arguments are sent to it, it will still continue to work, how to make it so that it would give an error when overloaded, and how to notice this very overload?
You need to use an IDE, then it will immediately be clear that you have made such mistakes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question