Jump to content

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
https://forums.phpfreaks.com/topic/301998-passing-this-to-a-sub-function/
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.

Sorry for my poor choice of words for "sub-functions".  I was trying to imply that these were only used to support another method.  I'll go with your optional parameter approach if I think it will be necessary to accept arbitrary IDs.

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.