4

I would like to have a function in my class that has a default parameter so that one can omit the argument if required. I want the default to be a variable stored in my class;

Hi why is this showing error messages in Aptana?

class property{
    private $id;
    function load_data($id = $this->id){
        //...blah blah blah
    }
}

Should I instead use

class property{
    static $id;
    function load_data($id = self::id){
        //...blah blah blah
    }
}

?

Thanks for the help

3 Answers 3

9

I'm pretty sure you can't do what you're looking for. Instead you should simply check to see if the argument has a value, and if it doesn't, assign the default value which is the object property.

class property{
    private $id;
    function load_data($id = null){
        $id = (is_null($id)) ? $this->id : $id;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Although I do like the ternary, I try to avoid setting a variable to itself.
2

You could do this:

class property
{
    private $id;

    function load_data($id = null){

        if (is_null($id)) {
            $id = $this->id;
        }

        //...blah blah blah
    }
}

4 Comments

Not that close, saw the AJAX notice before I hit submit. ;-)
@JackMahoney: haha, sarcasm? If you found one of our answers acceptable, please accept one.
@MikePurcell nah it was just funny to see. Accepted answer above but yours is just the same so thanks any way
@JackMahoney: No problem, important thing is you got your question answered.
0

I know its an old question but I came up on it searching for the same kind of thing and the answer is yes you can do it, as long as you define it as a constant:

class property{
    const $id;
    function load_data($id = self::id){
        //...blah blah blah
    }
}

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.