0

I have this code:

class foo
{
    public function __construct
    (
        $bar[var1]  = 0,
        $bar[var2]  = 0,
        $bar[var3]  = 0
    )
    {
        /* do something */
    }
}

and I get this error:

Parse error: syntax error, unexpected '[', expecting ')' in $this on line 5

and I have no idea about whats wrong.

EDIT:

I want to initialize the class like this: $instance = new foo($bar) ($bar is an array)

Because the class would expect many arguments, and I can easily return the array from the constructor. Let me know if this is not a good idea.

2
  • this being the EXACT method of giving space in actual code? Commented Apr 26, 2012 at 8:47
  • 1
    What are you trying to do? For instance, how are you planning to call this function? Commented Apr 26, 2012 at 8:48

5 Answers 5

8

Why are you trying to create an array in the function argument definition? That makes no sense and you cannot do this.

If you want $bar to be an argument but ensure some values exist (i.e. default values), do it like this:

public function __construct($bar)
{
    if(!isset($bar['var1'])) $bar['var1'] = 0;
    if(!isset($bar['var2'])) $bar['var2'] = 0;
    if(!isset($bar['var3'])) $bar['var3'] = 0;

    /* do something */
}

or in a more compact way:

public function __construct($bar)
{
    $bar = array_merge(array('var1' => 0, 'var2' => 0, 'var3' => 0), $bar);
    /* do something */
}
Sign up to request clarification or add additional context in comments.

1 Comment

Shorter way of writing it without the ifs: $bar = array_merge(array('var1'=>0, 'var2'=>0, 'var3'=>0), $bar);. But +1.
1
class foo
{
    public function __construct($bar = array())
    {
        $bar += array(
            "var1" => 0,
            "var2" => 0,
            "var3" => 0
        );

        /* do something */
    }
}

Comments

1
class foo
{
    public function __construct()
    {
        $bar = func_get_args();
    }
}

Comments

1

you cannot do that you should pass the array as a whole. also the keys have to be quoted

public function __construct($bar)
    {
        $bar['var1']  = 0;
        $bar['var2']  = 0;
        $bar['var3']  = 0;

        /* do something */
    }

Comments

1
class foo
{
    public function __construct($bar = array('var'=>0, 'var2'=>0, 'var3'=>0))
    {
        var_dump($bar);
    }
}

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.