I
I
ibr_982018-04-05 21:06:46
PHP
ibr_98, 2018-04-05 21:06:46

How can I make it so that it would not throw an error when I did not specify one of the function arguments?

Hello!
this code throws an error because I did not specify the second function argument, how to make it so that it does not give an error?
ps I'm just writing a framework for working with vk api, there are times when, for example, you need to specify only $user_id or only $chat_id

function func($user_id, $chat_id) {
  return $user_id;
}
echo func($user_id = 10) 
//ошибка:
//Warning: Missing argument 2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2018-04-05
@sidni

function func($user_id, $chat_id=0) {
  return $user_id;
}

D
Dmitry Entelis, 2018-04-05
@DmitriyEntelis

there are times when, for example, you need to specify only $user_id or only $chat_id

Do not forget about SOLID - if you have a function for which only $user_id is enough - it should have only $user_id in its arguments.
Formal answer to the question: either because sidni wrote it or if there are many arguments
function func(array $options) {
  return $options['user_id'];
}

echo func( ['user_id' => '111'] );

but here it is easy to get confused in the variables and in the end you will come to
trait init {
    function __construct(array $data) {
        foreach ($data as $key => $value) {
            if (property_exists(__CLASS__, $key)) {
                $this->$key = $value; 
            } else {
                throw new \Exception($key . ' undefined');
            }
        }
    }
}

class FuncOptions  {
    use init;
    public $user_id;
    public $chat_id;
}

function func(FuncOptions $options) {
  return $options->user_id;
}

echo func(new FuncOptions(['user_id' => '111']) );

and there you will discover factories and other patterns...
so it's better to write simple and understandable functions))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question