0

I am not new to php, but I find there optional parameters to be a bit ... unique, or maybe its just me.

If I have the following:

class SomeClass{
    public function some_method($required_param, $optional_array = array()){
        var_dump($optional_array); exit;
    }
}

Then do something like:

$test = new SomeClass();
$test->some_method('required', array('optional'));

I get back as a var_dump array(0){}.

I have even tried:

$test = new SomeClass();
$array = array('optional')
$test->some_method('required', $array);

With the same result. Is it because I am already defining that $optional_array is already set as a empty array? I swear this is how you set optional parameters, according to example 3 So why is it sticking with the default empty array? why is it not seeing that hey, this is already set.

1
  • 1
    Try var_dump($optional_array); It is not a function. Commented Jan 15, 2014 at 23:38

3 Answers 3

1
class SomeClass{
    public function some_method($required_param, $optional_array = array()){
        var_dump($optional_array); exit;
    }
}

Use var_dump($optional_array); not var_dump($optional_array());

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

2 Comments

So I realized my mistake >.> thank you. And I just tried it. same issue. Do I need to pass in by reference?
@user3200412 What do you mean by same issue? I've tried your code and it works perfect now.
0

You are trying to access your array as if it were a function. So remove the () and it will work:

var_dump($optional_array);

instead of

var_dump($optional_array());

Comments

0

You've got an extraneous set of parentheses on your var_dump. It's trying to call an anonymous function passed in as an array.

Try this:

class SomeClass{
    public function some_method($required_param, $optional_array = array()){
        var_dump($optional_array);
    }
}

$test = new SomeClass();
print "one\n";
$test->some_method('required', array('optional'));
print "two\n";
$test->some_method('required');

The output on my machine is:

one
array(1) {
  [0]=>
  string(8) "optional"
}
two
array(0) {
}

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.