NotionCommotion Posted August 25, 2016 Share Posted August 25, 2016 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? } } Quote Link to comment https://forums.phpfreaks.com/topic/301998-passing-this-to-a-sub-function/ Share on other sites More sharing options...
Psycho Posted August 25, 2016 Share Posted August 25, 2016 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. Quote Link to comment https://forums.phpfreaks.com/topic/301998-passing-this-to-a-sub-function/#findComment-1536625 Share on other sites More sharing options...
NotionCommotion Posted August 25, 2016 Author Share Posted August 25, 2016 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. Quote Link to comment https://forums.phpfreaks.com/topic/301998-passing-this-to-a-sub-function/#findComment-1536627 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.