Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php redeclaring function like in java [duplicate]

Possible Duplicate:
php function overloading

I want to redeclare function such like this:

class Name{
    function a(){ something; }
    function a($param1){ something; }
}

but it returns

Fatal error: Cannot redeclare Name::a()

In java it just works. How can I do this in PHP?

like image 261
Maximus Avatar asked Jan 31 '26 18:01

Maximus


2 Answers

Use default parameters:

class Name{
    function a($param1=null){ something; }
}

If no parameter is passed to Name::a() it will assign a $param1 has a value of null. So basically passing that parameter becomes optional. If you need to know if it has a value or not you can do a simple check:

if (!is_null($param1))
{
 //do something
}
like image 182
John Conde Avatar answered Feb 02 '26 10:02

John Conde


You won't redeclare a function. Instead you can make an argument optional by assigning a default value to it. Like this:

function a($param1 = null){ something; }
like image 38
datasage Avatar answered Feb 02 '26 09:02

datasage