Jump to content

Passing $this to a sub-function


NotionCommotion

Recommended Posts

Is it generally considered good practice to explicitly pass $this arguments to sub-functions, or is it okay for the sub-function to directly get the value from $this?  At least today, updateDB() will only use $this->id.

class foo
{
    private $id;
    public function __construct($id)
    {
        $this->id=$id;
    }
    
    public function updateValue($value)
    {
        // ...
        $this->updateDB($value,$this->id);
        // ...
    }

    private function updateDB($value,$id)
    {
        // Or should I just use $this->id?
    }
}  
Link to comment
Share on other sites

They are not 'sub-functions', they are methods within a class. And the variables defined for the class (such as $id) are properties. One of the benefits/reasons for having properties is so that you do not need to pass them between methods because they can be directly accessed via $this. And, passing $this from one method to another could only cause problems that I can see.

 

So, remove $id from the parameter list for the updateValue() method and reference it via $this->id. But, if you have any reason to call updateValue() and pass arbitrary id values, then you could make it an optional parameter. If no value passed used $this->id, else use the passed value.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.