Search code examples
phpoopclassclass-design

How to set a method's default argument to a class member


I have this inside a php class:

$this->ID = $user_id;

public function getUserFiles($id = $this->ID) { } // error here

But apparently I am not allowed to use a property in this way. So how would I go about declaring that the default value of the method argument should be the value of the ID property?

There must be a better way than this:

$this->ID = $user_id;

public function getUserFiles($id = '') {
    $id = ($id == '') ? $this->ID : $id;
}

Solution

  • I usually use null in this situation:

    public function getUserFiles($id = null)
    {
        if ($id === null) {
            $id = $this->id;
        }
        // ...
    }