1

I've got just one question -> is it good to have all parameters defined with default values in a function. I think it is a bad practice but I have a little argument with my colleague.

So is either:

public function getTestByUser($int_user_id, $limit, $offset)

or

public function getTestByUser($int_user_id = 0, $limit = 0, $offset = null)

better / nicer?

And why do you think so.

Thanks in advance.

2
  • 1
    it will save you from getting unintended results - however also will hide the processing errors,, which might teach you lots of things. Commented May 23, 2017 at 10:46
  • For calling function i think ` public function getTestByUser($int_user_id = 0, $limit = 0, $offset = null)` This is better with Default Argument Value Because when we do not pass variable value as function parameter it takes default value Commented May 23, 2017 at 10:52

1 Answer 1

2

It depends on your needs. Using default values for function variables is actually not a bad practice.

You shouldn't variable types as names. You can use PHP7's scalar type declaration feature.

e.g:

public function getTestByUser(int $userId, int $limit = 0, int $offset = null)

Dont' forget to add declare(strict_types=1); to top of your php file. Using strictly defined variable types make your code more solid.

Sign up to request clarification or add additional context in comments.

2 Comments

I agree with your point but why should a userId be 0? I'd rather take the "processing" error in calling the function wrongly instead of getting results which I dont know of where they're coming from
Right, you shouldn't use a default value for a userId. I fixed the code. Don't use default value if a varaible mandatory and don't work without a value (e.g: user id)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.