0

I have a function that looks somewhat like this:

function name( param1 = default, param2 = default, param3 = default) {...}

I'm calling the function by passing elements of an array as the parameters like this:

name( $param['foo'], $param['bar'], $param['hello'] );

My question is -- if one (or more) of the elements passed in the function call is undefined, how is it handled within the function itself? I ask because I am trying to call the function but I have no way of knowing if any of the elements are defined.

Inside of the function, I tried debugging a parameter passed through using isset(), is_null(), and empty() and I got false, true, and true respectively. This leads me to believe that since something is actually being passed in, the default value is not set. If anyone could explain how something like this is handled I would appreciate it.

6
  • Hm, if you pass array values, why just not pass the array itself? Commented Aug 19, 2015 at 21:03
  • possible duplicate of How do I pass undefined vars to functions without E_NOTICE errors? Commented Aug 19, 2015 at 21:04
  • @bksi It's totally possible but I was thinking if I knew exactly which array elements I would need, I might as well just pass those. Commented Aug 19, 2015 at 21:05
  • You can check them after passing in the method you pass them. Commented Aug 19, 2015 at 21:06
  • The default value is only used if no argument was passed. If you pass an argument, it will be used, even if it's undefined. Commented Aug 19, 2015 at 21:08

3 Answers 3

1

The function generally has no clue, and generally doesn't care, WHERE an argument came from. e.g.

$x = 2;
foo($x);
foo(2);

As far as foo() is concerned, it'll just see 2 come in, and nothing will tell it "this 2 was hardcoded" or "this 2 was passed in via a variable".

If you pass in an undefined variable, then the function itself will see a null value arrive, and PHP will spit out a warning about using the undefined variable, BEFORE the function code ever has a chance to start executing.

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

Comments

1

The short answer is that it is passing, NULL which is a constant value designated to represent a null or uninitialized value.

Comments

0

Calling an undefined index in an array results in a warning.

Two rules for you:

  • Pass/use only defined things
  • Never disable warnings/errors

Example:

$params = ['foo' => 1, 'bar' => null, 'nextKey' => null];

A common approach is to pass the (sub)array:

myMethod($params);

Your method takes the elements it need.

Comments

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.